The first value is the accumulator, the second one is the current value.
The starting value should be provided for the accumulator:
//0 at the end is the starting value
const sum = myArray.reduce((acc,element)=>acc + element,0)
Notice the last value as 1 in the following paragraph, because it is a multiplication.
const numbers = [5, 7, 2, 40, 23, 14, 8, 4, 11];
const product = numbers.reduce((acc, x) => {
console.log(`acc is ${acc}, x is ${x}, acc * x = ${acc * x}`);
return acc * x;
}, 1);
console.log(product);
acc is 1, x is 5, acc * x = 5
acc is 5, x is 7, acc * x = 35
acc is 35, x is 2, acc * x = 70
acc is 70, x is 40, acc * x = 2800
acc is 2800, x is 23, acc * x = 64400
acc is 64400, x is 14, acc * x = 901600
acc is 901600, x is 8, acc * x = 7212800
acc is 7212800, x is 4, acc * x = 28851200
acc is 28851200, x is 11, acc * x = 317363200
317363200
const map = (arr, func) => arr.reduce((acc, x) => [
...acc,
func(x),
], []);
// testing if it works:
// Should be [2, 4, 6]
console.log(map([1, 2, 3], (x) => x * 2));
// Should be [-5, -6, -7, -8, -9, -10]
console.log(map([5, 6, 7, 8, 9, 10], (x) => -x));
// Should be ['A', 'B', 'C', 'D']
console.log(map(['a', 'b', 'c', 'd'], (x) => x.toUpperCase()));
[ 2, 4, 6 ]
[ -5, -6, -7, -8, -9, -10 ]
[ 'A', 'B', 'C', 'D' ]