In java I'm using streams to calculate the sum of a list of orders like this:
orders.stream().mapToInt(Order::getQuantity).sum()
I'm wondering whether there is an equally elegant way to do this in javascript when iterating over an array of Order instances. Essentially an array like this:
[{quantity: 10}, {quantity: 20}, {quantity: 15}, ...]
I have something like this so far, but I'm wondering if it could be even shorter:
orders.map((order)=>order.quantity).reduce((a, b)=> a+b,0);
You do not need to use map
just do:
orders.reduce((a, b) => a + b.quantity, 0));
console.log([{
quantity: 10
}, {
quantity: 20
}, {
quantity: 15
}].reduce((a, b) => a + b.quantity, 0));