数组中的每一项按照某个属性分组
var wang = [{g: 1, c:"aa"}, {g: 1, c: "bb"}, {g: 4, c: "cc"}, {g: 2, c: "dd"}, {g: 2, c:"ee"},
{g: 2, c: "ff"}, {g: 3, c: "gg"}];
var xxx = wang.map(function(item) {
return item.g;
});
console.log("xxx: ",xxx);
var yyy = [];
xxx.forEach(function(item) {
if (yyy.length > 0) {
if (yyy.indexOf(item) > -1) {
return
} else {
yyy.push(item);
}
} else {
yyy.push(item);
}
});
console.log("yyy: ",yyy);
var zzz = [];
yyy.forEach(function(item) {
zzz.push(wang.filter(function(apItem) {
return apItem.g == item;
}));
})
console.log("zzz: ",zzz);
简化附带说明版本:
var wang = [{g: 1, c:"aa"}, {g: 1, c: "bb"}, {g: 4, c: "cc"}, {g: 2, c: "dd"}, {g: 2, c:"ee"},
{g: 2, c: "ff"}, {g: 3, c: "gg"}];
//提取所有g值得数组
var xxx = wang.map(function(item) {
return item.g;
});
console.log("xxx: ",xxx);
//返回去重之后的数组。
var yyy = [];
xxx.forEach(function(item) {
!(yyy.indexOf(item) > -1) && yyy.push(item)
});
console.log("yyy: ",yyy);
var zzz = [];
yyy.forEach(function(item) {
//每次循环都会分组,分好的组分别push到zzz
zzz.push(wang.filter(function(apItem) {
return apItem.g == item;
}));
});
console.log("zzz: ",zzz);