Immutable-js: Best way to accomplish sum()?

Created on 27 Sep 2015  路  3Comments  路  Source: immutable-js/immutable-js

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?

Most helpful comment

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

All 3 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

s-panferov picture s-panferov  路  4Comments

kopax picture kopax  路  3Comments

Haroenv picture Haroenv  路  3Comments

jbonta picture jbonta  路  3Comments

sterpe picture sterpe  路  4Comments