I have an array of objects, where I want to find the objects having same value for name property and then merge them into single object by adding their values & subvalues.
const arr = [
{ id: 1, name: 'a', value: 2, subvalue: 3 },
{ id: 2, name: 'b', value: 4, subvalue: 3 },
{ id: 3, name: 'c', value: 4, subvalue: 3 },
{ id: 4, name: 'b', value: 3, subvalue: 4 }
]
Expected output
[
{ id: 1, name: 'a', value: 2, subvalue: 3 },
{ id: 2, name: 'b', value: 7, subvalue: 7 },
{ id: 3, name: 'c', value: 4, subvalue: 3 }
]
The id of the new object can either be 2 or it can be 4. So it doesn’t matter much. I have tried using filter, but not able to find a solution which suits my requirement
2
Answers
Using only
Array#reduce
, see if thename
of thecurr
ent object is already present in theacc
umulator withArray#findIndex
, then Values and Subvalues should be accumulated respectively with the current object Values and Subvalues, Otherwise add the currentobj
ect in theacc
umulator:if you don’t want to maintain the first (original)
id
and would rather use the id from the last (most recent) merged object, just replace...acc[index]
with...cur
when you merge them.you can use
reduce
to group byname
and then get the values array of the grouped object usingObject.values
or the whole if else logic be one-lined but less readable