JavaScript’s Reduce Method
The reduce method was something that I’ve struggled with fully understanding. Even now, I have trouble being fully comfortable implementing reduce in my algorithms practice. Let’s get down to it.
According to MDN’s (Mozilla Developer Network) docs, the syntax for the reduce method is :
arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
Namely, the reduce method takes an array and turns it into a single value. A simple way to understand this is when you have an array of numbers and you want to return the sum of all those numbers. The reduce method can do that for you.
The first argument in a reduce method is a callback function. To understand this, I felt like it was best to define the callback in a separate variable and pass it as a parameter to the reduce method.
For instance:
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
This takes all the numbers in array1 and adds them and returns a value of 10.
The accumulator starts at 0, and is the sum of the values that it’s previously added up. In this case, it’ll go from: 0 → 1 → 3 → 6 → 10. The current value is just the current value you’re adding up. So: 1 → 2 → 3 → 4.
To step things up a notch, you can also start at an initial value.
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
The current value will still be the same: 1 → 2 → 3 → 4. But the accumulator will change: 5 → 6 → 8 → 11 → 15.
The index
is the index of the current element being process in the array, or the index of the current value. The array
is the source array, unaltered. I personally haven’t used index or array much, so I’m not going to go into detail for these two parameters since I haven’t used them practically.
Hope that clears things up a bit in case you were also struggling with reduce!
Stay safe everyone!