元素分组
通过 reduce 分组
function groupBy(objectArray,property){
return objectArray.reduce(function(accumulator,currentValue,index,arr){
const key = currentValue[property];
if(!accumulator[key]){
accumulator[key] = [];
}
accumulator[key].push(currentValue);
return accumulator;
},{});
}
const array = [
{ name: "Alice", age: 21 },
{ name: "Max", age: 20 },
{ name: "Jane", age: 20 },
];
const result = groupBy(array,'age');
console.log(result);