reduce() method in JavaScript
Let's see what MDN has to say: The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise, the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
pretty intense ??.
Actually, this one is quite tricky as compared to map and filter.
for now understand this: Each element of the array passes through the function provided by us in order to give a single value as output.
The best way to understand is through examples. So, let's get the ball rolling:
Example 1: Given an array of numbers, return the sum of all numbers?
const numbersArray = [1, 6, 9, 4];
//we'll understand using normal function:
function sum(accumulator, currentValue){
return acc+current;
}
const output = numbersArray.reduce(sum);
console.log(output)
Result: 20
So, what the heck just happened. Don't worry, just listen to me carefully and while doing that refer to the above example.