I have this array
const data = [
{"One",prix:100},
{"Two",prix:200},
{"Three",prix:300}
]
and I want to get the sum of all those prix like this:
sum = 600
I have this array
const data = [
{"One",prix:100},
{"Two",prix:200},
{"Three",prix:300}
]
and I want to get the sum of all those prix like this:
sum = 600
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
arr.reduce(callback, initialValue);
reducer will only return one value and one value only hence the name reduce. Callback is a function to be run for each element in the array.
and Function arguments function(total,currentValue, index,arr):
Argument Description
total Required.The initialValue, or the previously returned value of the function
currentValue Required.The value of the current element
currentIndex Optional.The array index of the current element
arr Optional.The array object the current element belongs to
in this example use this code:
const data = [
{title:"One",prix:100},
{title:"Two",prix:200},
{title:"Three",prix:300}
];
const result = data.reduce((total, currentValue) => total = total + currentValue.prix,0);
console.log(result); // 600
const sum = data.map(datum => datum.prix).reduce((a, b) => a + b)
data.reduce((a, b) => a + b.prix,0)map and reduce is more modular and doesn't require the initializer (0). It's also easier to refactor into a transducer or other functions with subsets/supersets of this functionality.