要求:
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
{ name: 'David', age: 25 },
{ name: 'Emily', age: 30 }
];
// Output: {
// 25: [{ name: 'Alice', age: 25 }, { name: 'David', age: 25 }],
// 30: [{ name: 'Bob', age: 30 }, { name: 'Emily', age: 30 }],
// 35: [{ name: 'Charlie', age: 35 }]
// }
代码:
let fn = (arr = []) => {
return arr.reduce((accumulator, currentValue) => {
return accumulator[currentValue.age]
? (accumulator[currentValue.age] = accumulator[currentValue.age].concat(currentValue))
: ((accumulator[currentValue.age] = [currentValue]));
}, {});
};
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
{ name: 'David', age: 25 },
{ name: 'Emily', age: 30 }
];
console.log(fn(people));
输出:
[ { name: 'Emily', age: 30 } ]
所谓上一次调用结果即你每一次
return
的值会交给下一次迭代,而在你的代码中第一次accumulator
是初始值{}
,而在你的return
语句是三元表达式,而表达式是赋值语句,赋值语句的结果是等号右侧的结果,一个是concat
,一个是[currentValue]
,这两个都是数组,它们作为下一次的accumulator
,所以你下一次迭代就不再是对象了。所以你需要把每次迭代的对象return
回去: