This question is come from how-to-sum-an-array-for-each-id-and-create-new-array-in-react,OP needs to sum data by id
const data = [{"id": "One", "number": 100},
{"id": "One", "number": 150},
{"id": "One", "number": 200},
{"id": "Two", "number": 50},
{"id": "Two", "number": 100},
{"id": "Three", "number": 10},
{"id": "Three", "number": 90}]
In order to do it,I just use a traditional way(check with if
) to do it with reduce()
let result2 = data.reduce((a, v) => {
let obj = a.find(i => i.id == v.id);
if (obj) {
obj.number += v.number;
} else {
a.push(v);
}
return a;
}, [])
console.log(result2);
And I found another answer is more elegant(one-liner):
let result3 = data.reduce((acc, {id, number}) => ({...acc, [id]: {id, number: acc[id] ? acc[id].number + number: number}}), {});
console.log(Object.values(result3));
The question is that when I ran the two methods seperately,I can got the expected result(jsfiddle1 and jsfiddle2)
However,if I ran them together,the seconds result(from result3
) is not as expected(jsfiddle 3)
I do not know why this happen,can anyone help me to analysis this?
Also,I want to know if there are a more elegant one-liner solution to do it.
Thanks in advance!