You can map
your object then reduce
it:
samplObject
=> [weight0, weight1, weight2]
[weight0, weight1, weight2]
=> weight0 + weight1 + weight2
This means you transform your initial list into a list of weights, then you sum the values one by one.
const sampleObject = [
{
suite: "Clubs",
weight : 10
},
{
suite: "Spades",
weight : 6
},
{
suite: "Hearts",
weight : 2
}
];
let sum = sampleObject.map( el=> el.weight).reduce( (a,b) => a+b);
console.log(sum)
Output :
18
Note :
In this particular example, map
is an overhead. You can calculate the sum easily :
let sum = sampleObject.reduce( (a,b) => a+b.weight,0);
But for more complex data structures, and in general, it's nice to have the concept of map-reduce
in mind.