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);