I'm transitioning my codebase from custom objects + Lodash and so far Immutable has replaced both perfectly. But there's ont thing I can't seem to do easily which is to get the sum of a List/Map. Currently doing this:
let total = 0;
entries.forEach(entry => total += entry.get('price'));
Is there anything similar to Lodash's sum like entries.sum('price') or entries.sum(entry => entry.get('price')) or something that I missed in the documentation?
I couldn't find any methods like sum but I guess the closest way to accomplish something like sum is to use the reduce method.
var entries = Immutable.fromJS([
{price: 1},
{price: 2},
{price: 3},
]);
var sum = entries.map(entry => entry.get('price')).reduce((prev, current) => prev + current);
console.log(sum); // 6
reduce is pretty much the standard way to do these aggregation operations in functional programming
Closing out. reduce is the way to go!
Most helpful comment
I couldn't find any methods like
sumbut I guess the closest way to accomplish something likesumis to use thereducemethod.