如何把数组内相同的值,组成新的数组
僵了大半天
//原始数组
let arr = [
{ name: 'book', number: 10 },
{ name: 'paper', number: 10 },
{ name: 'ruber', number: 10 },
{ name: 'book', number: 20 },
{ name: 'paper', number: 40 },
{ name: 'ruber', number: 50 },
{ name: 'book', number: 70 },
{ name: 'paper', number: 80 },
{ name: 'ruber', number: 90 },
];
//目标转换成这样
let newArr = [
{ name: 'book', value: [10, 20, 70] },
{ name: 'ruber', value: [10, 40, 80] },
{ name: 'paper', value: [10, 50, 90] },
];
回答
function group(arr) {
return Object.values(arr.reduce((result, item) => {
const { name, number } = item;
const { values = [] } = result[name] || {};
values.push(number);
result[name] = { name, values };
return result;
}, {}));
}
// TEST
group(arr);