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 } ]
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]]
2-We flatten the list with the method flat():
.flat() // result: [20, 4, 40, 10]
3-We sum all values with the reduce() method:
.reduce((a, b) => a + b) // result: 74
In the end we get this code:
let total = products.map(product =>([product.vat,product.price])).flat().reduce((a, b) => a + b)
Thank you!
Top comments (0)