假设我们有一个对象数组,其中包含一些人进行的一些随机交易的信息-
const transactions = [{ name: 'Rakesh', amount: 1500 }, { name: 'Rajesh', amount: 1200 }, { name: 'Ramesh', amount: 1750 }, { name: 'Rakesh', amount: 2100 }, { name: 'Mukesh', amount: 1100 }, { name: 'Rajesh', amount: 1950 }, { name: 'Mukesh', amount: 1235 }, { name: 'Ramesh', amount: 2000 }];
我们需要编写一个函数,该函数接受此数组并聚合并返回不同对象中唯一人员的交易额。
因此,让我们为该函数编写代码-
const transactions = [{ name: 'Rakesh', amount: 1500 }, { name: 'Rajesh', amount: 1200 }, { name: 'Ramesh', amount: 1750 }, { name: 'Rakesh', amount: 2100 }, { name: 'Mukesh', amount: 1100 }, { name: 'Rajesh', amount: 1950 }, { name: 'Mukesh', amount: 1235 }, { name: 'Ramesh', amount: 2000 }]; const aggregateArray = arr => { return arr.reduce((acc, val) => { const index = acc.findIndex(obj => obj.name === val.name); if(index !== -1){ acc[index].amount += val.amount; }else{ acc.push({ name: val.name, amount: val.amount }); }; return acc; }, []); }; console.log(aggregateArray(transactions));
输出结果
控制台中的输出将为-
[ { name: 'Rakesh', amount: 3600 }, { name: 'Rajesh', amount: 3150 }, { name: 'Ramesh', amount: 3750 }, { name: 'Mukesh', amount: 2335 } ]