Rupur
1
- Goal: Hi guys, I have a table with names and prices in it. I want to sum the prices column but depending on the name column, basically like this:
A - 500
B - 300
C - 400
B - 900
G - 100
C - 300
Now I want to do something like "Give me the sum of everything with the name B", so the result should be 1200
I can sum up a column like this: _.sum(table1.data.map(i=>parseFloat(i.price)))
But how can I built in the additional condition?
pyrrho
2
The nature of the map function is that it will return a value for every item in your array. So you can approach this in (at least) two ways.
- filter the initial array with your condition and then only map for the prices over the result:
_.sum(table1.data.filter(i=>i.name === yourConditionalValue).map(i=>parseFloat(i.price)))
- return 0 in the mapping function when your condition is not met:
_.sum(table1.data.map(i => {
if(i.name === yourConditionalValue) return parseFloat(i.price)
else return 0
}))
I think #1 is a bit more logical to follow for readability.