It doesn’t just “produce a bunch of numbers” and reduce doesn’t just “add them all together”. This is why I asked you about the function , whether you understood that they were arguments
If you’re saying you understand map, then you must understand that map is a function that you give an array + a callback function to. Then it runs that callback function on every element in the array. The callback function takes the current element, does {something} to it and returns that, like
function (element) {
return /* Do something to the element */
}
Most of the array methods are exactly the same pattern, you give them an array and a function and they run that function on every element.
Reduce isn’t different, it’s not magic, you don’t have to pray for insight.
Map takes an array and returns that same array after it’s had the function ran for every element.
Reduce takes an array and a value (an accumulator), then returns that accumulator after it’s had the function ran for it and every element.
The callback function takes the value and the current element, does {something} involving both, and returns the result of that. When it runs on the next element, that result is the new value of accumulator, and so on.
Reduce takes two arguments: the first is the callback. The second is value you want to start the accumulator at. If you miss the second value out, reduce will use the first value in the array to start the accumulator
function (accumulator, element) {
return /* result of doing something to both */
}
Like
function map(array, callback) {
let outputArray = [];
for (let i = 0; i < array.length; i++) {
outputArray.push(callback(array[i]);
}
return outputArray;
}
function reduce(array, callback) {
let accumulator = array[0]
for (let i = 1; i < array.length; i++) {
accumulator = callback(accumulator, array[i])
}
return accumulator;
}
console.log(map([1,2,3,4], (num) => num * 2))
// [2, 4, 6,]
console.log(reduce([1,2,3], (acc, num) => acc * num))
// 6