So what s a and b in the reduce() function? I have o idea how they are getting 16.
I understand that it is a function passing a and b and adding β¦ but what is a and b?
Hello
a : total Required. The initialValue , or the previously returned value of the function
b : currentValue Required. The value of the current element
So first a is 0 and b is arr[0]
Then a = 0 + arr[0] and b = arr[1]
After a = arr[0] + arr[1] and b = arr[2]
Until the end , the total will be accumulated in a.
i still dont get it⦠why a and b? i dont understand there placement or what it means.
a + b could mean anything. a + b is only two values how does that function total up to 16? it make no sence at all.
Hi ainneo, hereβs the mdn documentation on reduce.
The exercise isnβt focused on the reduce function. However if you are curious about reduce, you can read about it in detail there.
Here is also a great resource:
Hi @ainneo,
It totals up to 16 because of this part of the problem:
console.log(sumOfTen([2, 5, 1, 5, 2, 1]));
When you call sumOfTen, you pass in the array: [2, 5, 1, 5, 2, 1]. If you add each of these #s up, it equals 16.
So how does it work? The βaβ is the accumulator and βbβ is the βcurrent valueβ of the array. Think of them like variables. You can actually use other variable names, but the project uses βaβ and βbβ.
Anyways, using the Array above: [2, 5, 1, 5, 2, 1], keep note of the a + b in (a, b) => a + b
. The a + b returns a value to store in βaβ for the next step.
So at the beginning, βaβ = a + b, and βbβ = 2. Again, βbβ keeps track of the current value of the array. Since βaβ, at the beginning, has no initial value, βaβ will simply = βbβ, in other words βaβ = 2.
On the next step, current value in the array is 5 -> so now βbβ = 5. Well, we know βaβ from last time is = 2
-
a + b = 2 + 5 = 7.
-
This 7 is then stored in βaβ for the next step.
On the next step, the current value in the array is now 1. so βbβ = 1. We know βaβ from last step is = 7.
-
a + b = 7 + 1 = 8.
-
The 8 is then stored in βaβ for the next step.
On the next step, the current value in the array is now 5 --> βbβ = 5. βaβ from previous step = 8
-
a + b = 8 + 5 = 13.
-
The 13 is then stored in βaβ for the next step.
On the next step, the current value is now 2 --> βbβ = 2. βaβ from previous step = 13.
-
a + b = 2 + 13 = 15.
-
The 15 is then stored in βaβ for the next step.
Finally, on the last value of the Array, βbβ = 1. βaβ from the previous step = 15.
- a + b = 15 + 1 = 16
Since we reached the end of the [2, 5, 1, 5, 2, 1] array, the .reduce returns the final value in βaβ, which is 16.
The goal of the project is to splice the Array so that the returned value is 10, rather than 16. So your goal is to get the [2, 5, 1, 5, 2, 1] Array to look like [2, 5, 2, 1] using the .splice method since 2 + 5 + 2 + 1 = 10
a and b are variable there names are not important.
Example: [1, 2 ,3].reduce((x, y) => x + y)
return 6