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
}
]
-------- APPROACH 2025 -------------
You can simply use the array functionality reduce. Basically the reducer function receives 2 parameters:
acc: it's the result of the past iterations
cur: The current iteration of the array
Also you can notice we have a 0 value as second option, this is the initialValue of acc.
products.reduce((acc, cur) => (cur.price + cur.vat) + acc, 0)
-------- APPROACH 2021 -------------
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)