How to get from this array
[
{name: "a", weight: 1},
{name: "b", weight: 3},
{name: "a", weight: 5},
{name: "b", weight: 7}
]
get this array(weight of duplicates summed)
[
{name: "a", weight: 6},
{name: "b", weight: 10}
]
You don't need any fancy Underscore stuff for this, you can do it all with a single
reduce
call:Then your array will be in
result.a
.Demo: http://jsfiddle.net/ambiguous/6UaXr/
If you must, you can use
_.reduce
instead of the nativereduce
.There are a couple tricks here:
reduce
memo caches the results by name in an object and in an array at the same time. Indexing by inm.by_name
gives you quick lookups but you want an array as the final result so we build that along the way too.m.by_name[e.name]
also updates the array.by_name
entries are created (and the references carefully shared) the first time we need them. We also initialize the cached weights with zero so that all the summarizing is done in a singlem.by_name[e.name].weight += e.weight
.Something like this should work using
groupBy
reduce
andpluck
:Note that we are
reduce
ing using native JavaScript reduce, if you want Underscore's reduce you need to chain inside before the_.pluck
, call.reduce
and then call.value
.