Shokwave - 3 months ago 34x

Javascript Question

I have been trying to get this right and was having issues so figured i should ask ppl with more experience. I have an array of objects lets say called items, and I need to sum up some of the properties across different objects in the array and sum them up those at the end. The user can make a few selections and i need to only sum up the only the chosen properties in the array they give me so i thought maybe to use the _.pick function in lodash. If possible i would like to do that in one loop since the items array could have upto a 1000 items. Here is an example:

`var items = [`

{'lightBlue':4, 'darkBlue':2, 'red':4, 'orange':6, 'purple':7},

{'lightBlue':6, 'darkBlue':5, 'red':1, 'orange':2, 'purple':3},

{'lightBlue':2, 'darkBlue':4, 'red':3, 'orange':4, 'purple':9}

]

var userSelectedColors = ['lightBlue', 'darkBlue'];

What I want to see is all the blue's summed up like:

`var summedUp = [{'lightBlue':12, 'darkBlue':11}];`

Then sum up the results to get the total no

`var totalCount = 23`

Whats the best and performant way to get this in lodash. The array of userSelectedColors could be 1 or any combination of the colors.

Please provide an example, thanks your helps appreciated!

Answer

Use `_.sumBy`

```
var totalCount = _.sumBy(userSelectedColors, function(prop) {
return _.sumBy(items, prop);
});
```

```
var items = [
{ 'lightBlue': 4, 'darkBlue': 2, 'red': 4, 'orange': 6, 'purple': 7 },
{ 'lightBlue': 6, 'darkBlue': 5, 'red': 1, 'orange': 2, 'purple': 3 },
{ 'lightBlue': 2, 'darkBlue': 4, 'red': 3, 'orange': 4, 'purple': 9 }
], userSelectedColors = ['lightBlue', 'darkBlue'];
var totalCount = _.sumBy(userSelectedColors, function(prop) {
return _.sumBy(items, prop);
});
console.log(totalCount);
```

`<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>`

Or you could iterate the other way around this way:

```
var totalCount = _.sumBy(items, function(obj) {
return _.sumBy(userSelectedColors, _.propertyOf(obj));
});
```

Source (Stackoverflow)

Comments