I have a collection which has a bunch of models which look like the following example:
{
metricName : 'clicks',
metricValue : 100
}
What I want is to search through the collection and consolidate all the models that have the same metricName into one model which has the sum of all the values.
So
{
metricName : 'clicks',
metricValue : 100
}
{
metricName : 'otherMetric',
metricValue : 100
}
{
metricName : 'clicks',
metricValue : 100
}
turns into
{
metricName : 'clicks',
metricValue : 200
}
{
metricName : 'otherMetric',
metricValue : 100
}
I’m trying to solve this as efficiently and easily as possible by using underscore.
I can see one solution is to use _.each and loop through and keep track of metric names while summing the values and eliminating dupes (sounds lame).
My question is if there is another, better way to do this using one of underscores other methods. I can see maybe map, find, findwhere, filter, etc might be options but I’m not sure.
You could do something cute with
groupByandreduce: