求教!js二维数组中,如何把具有相同种类name的值筛选出来,组成三维数组

具体这样的,比如varcollege=[[{name:'北京'},{city:'西安'}],[{name:'上海'},{city:'包头'}],[{name:'广州'},... 具体这样的,比如var college = [[{name:'北京'}, {city:'西安'}],
[{name:'上海'},{city:'包头'}],
[{name:'广州'},{city:'福州'}],
[{name:'北京'},{city:'广州'}],
[{name:'广州'},{city:'太原'}],
[{name:'上海'},{city:'昆明'}]];
要得到这种:
[[
[{name:'北京'}, {city:'西安'}],
[{name:'北京'}, {city:'广州'}]
],
[
[{name:'上海'},{city:'包头'}],
[{name:'上海'},{city:'昆明'}]
],
[
[{name:'广州'},{city:'福州'}],
[{name:'广州'},{city:'太原'}]
]];
展开
 我来答
yugi111
2017-07-03 · TA获得超过8.1万个赞
知道大有可为答主
回答量:5.1万
采纳率:70%
帮助的人:1.3亿
展开全部
var college = [
    [{name:'北京'},{city:'西安'}],
    [{name:'上海'},{city:'包头'}],
    [{name:'广州'},{city:'福州'}],
    [{name:'北京'},{city:'广州'}],
    [{name:'广州'},{city:'太原'}],
    [{name:'上海'},{city:'昆明'}]
];

var result = [];
for(var i = 0;i<college.length;i++){
    var ci = college[i], obj = ci[0];
    var isExisted = false;
    for(var j =0;j<result.length;j++){
        var rj = result[j];
        if(rj.type==obj.name){
            rj.push(ci);
            isExisted = true;
            break;
        }
    }
    if(!isExisted){
        var tmp = [ci];
        tmp.type = obj.name;
        result.push(tmp);
    }
}
college = result;
console.log(college);
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式