DEV Community

Cover image for Summing properties from a list of objects in JS
Alisson Zampietro
Alisson Zampietro

Posted on

Summing properties from a list of objects in JS

Let's assume that we have an array of objects called products with the following structure:

let products = [ { "name": "Item 1", "price": 20, "vat": 4 }, { "name": "Item 2", "price": 40, "vat": 10 } ] 
Enter fullscreen mode Exit fullscreen mode

So, if we want to sum all numbers (price+vat) let's make the following steps:

1-We call the map() function to generate an array with the numeric values that we want to sum:

products.map( product => ([product.vat, product.price]) ) // result: [[20, 4], [40, 10]] 
Enter fullscreen mode Exit fullscreen mode

2-We flatten the list with the method flat():

.flat() // result: [20, 4, 40, 10] 
Enter fullscreen mode Exit fullscreen mode

3-We sum all values with the reduce() method:

.reduce((a, b) => a + b) // result: 74 
Enter fullscreen mode Exit fullscreen mode

In the end we get this code:

let total = products.map(product =>([product.vat,product.price])).flat().reduce((a, b) => a + b) 
Enter fullscreen mode Exit fullscreen mode

Thank you!

Top comments (0)