0
JavaScript Problem #2 (arrays, reduce)
Problem: What is the value of result? const f = (r, v) => r + v; const result = [1, 2, 3].reduce(f, 0); The answer is 6 but I don't understand why..
2 Answers
+ 3
It will just reduce a list into simply a number according to the function used!
Here, it is saying to add all the elements!
=> What is going on?
[1,2,3]
First and second elements are added! (1+2)
[3,3]
Then again the first and second elements are added! (3+3)
= 6
=> what is the meaning of 0 at the end?
It is just to add another number to the function's task!
if it was 1 instead of 0
then the answer would have been 7
The first and second elements are applied to the function again and again until we recieve a number
+ 2
Zone Reduce() can be strange for beginners because the function name and parameters are not intuitive.
C# has an equivalent LINQ method called Aggregate() which I find to be more intuitively named.
Let's start with stating what reduce is doing here, then we will see how it does it.
Reduce returns the sum of all items in the array.
It does this by iterating through each array value, one at a time, and adds it to the accumulated total along the way. The accumulated total starts as 0. The add logic is performed in a separate function assigned to f.
The code below is equivalent to the code in your question:
----
function add(nums)
let sum = 0
for(let num of nums) {
sum = sum + num
}
return sum
}
const result = add([1, 2, 3]) // 6
----
Can be rewritten as:
----
function add(num, sum) {
return num + sum
}
const startSum = 0
const result = [1, 2, 3].reduce(add, startSum)
----
See if you can mentally map the corresponding parts between the examples and deduct what is going on.



