So I have an array and I want to merge or totals it base on its name
Here is an example data:
[
{
name: "Name1",
amt : 100,
tax : 10,
total : 110
},
{
name: "Name2",
amt : 50,
tax : 5,
total : 55
},
{
name: "Name1",
amt : 70,
tax : 7,
total : 77
}
]
Is there a method or reference where I can produce an output like this?
[
{
name: "Name1",
amt : 170,
tax : 17,
total : 187
},
{
name: "Name2",
amt : 50,
tax : 5,
total : 55
}
]
2
Answers
You could reduce each object into a map by the key value. For each item, loop over the keys and ignore the
key
param.Sum the incoming
item[k]
onto theexisting[k]
entry.Finally, return the
values()
of theMap
and spread the iterator into a newArray
object.Use
Array::reduce()
to construct a new array, remember items by the name in a map and them into the result array and use the map to update items with new totals: