求教!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:'太原'}]
]]; 展开
[{name:'上海'},{city:'包头'}],
[{name:'广州'},{city:'福州'}],
[{name:'北京'},{city:'广州'}],
[{name:'广州'},{city:'太原'}],
[{name:'上海'},{city:'昆明'}]];
要得到这种:
[[
[{name:'北京'}, {city:'西安'}],
[{name:'北京'}, {city:'广州'}]
],
[
[{name:'上海'},{city:'包头'}],
[{name:'上海'},{city:'昆明'}]
],
[
[{name:'广州'},{city:'福州'}],
[{name:'广州'},{city:'太原'}]
]]; 展开
2个回答
展开全部
var college = [
[{name:'北京'}, {city:'西安'}],
[{name:'上海'},{city:'包头'}],
[{name:'广州'},{city:'福州'}],
[{name:'北京'},{city:'广州'}],
[{name:'广州'},{city:'太原'}],
[{name:'上海'},{city:'昆明'}]
];
//先用map结构记录
function arrayToMap(data) {
//非数组或数据长度为0不处理
if(!data instanceof Array || data.length == 0) {
return {};
}
var map = {};
for(var i=0;i<data.length;i++) {
if(!data[i] instanceof Array || data.length < 2) {
continue;
}
var name = data[i][0].name;
if(name != undefined) {
if(map[name] == undefined) {
map[name] = [];
}
map[name].push(data[i]);
}
}
return map;
}
//把map转成数组
function mapToArray(data) {
if(data == undefined) {
return [];
}
var array = [];
for(p in data) {
array.push(data[p]);
}
return array;
}
//测试
var map = arrayToMap(college);
var array = mapToArray(map);
console.log(array);
展开全部
function merge(college) {
var res = [],
c = [];
Array.prototype.forEach.call(college, function(item) {
var i = c.indexOf(item[0].name);
if (i < 0) {
c.push(item[0].name);
var a = [];
a.push(item);
res.push(a);
} else {
res[i].push(item);
}
});
return res;
}
var res = merge(college);
res.forEach(function(row) {
console.log(row);
})
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询