The challenge offers this example of how to use reduce to _subtract_ all the values of an array:
var singleVal = array.reduce(function(previousVal, currentVal) {
return previousVal - currentVal;
}, 0);
My question is: why wouldn’t the same code work by replacing the - (minus) sign with + (plus) in order to add the values of an array?
Well, this isn’t quite right. The callback isn’t written correctly. I assume something happened when you were copying/pasting from the problem this time around.
Same for me – with the original code I sent, no problem. But the actual example code in the challenge seems to be missing a “currentVal” term. Is this something I should report?
Hi.
Note that if array is declared as var array = […values…], this code work singleVal = array.reduce(function(previousVal, currentVal){ return previousVal+currentVal;});
and returns the correct value.
I copied and pasted it in nodejs, I just added a declaration of the array (var array = [125, 12, 35, 40];)
and it’s returned 212 (the sum) !
var singleVal = array.reduce(function(previousVal,currentVal){return previousVal + currentVal;});
array = singleVal;
I was struggling to understand why the code was not working as well based on the example, but
all I did was make
array = singleVal; and the code worked, the original code at the bottom is
singleVal = array;
The part that I re-read in the instruction that made me think to do this was “Use the reduce method to sum al the values in array and assign it (array) to singleVal.”
If someone wants to clarify why that worked while singleVal = array; failed I would like to know also. I remember that everything to the right of the = sign is already resolved before the value is assigned to the left so… since singleVal was already assigned(resolved) in the code above: var singleVal = array.reduce(function(previousVal,currentVal){return previousVal + currentVal;});
I decided to switch it and it worked. Hope this helps.
const singleVal = array.reduce((a, b) => a - b, 0)
p.s: you can skip initial value in both cases: for + and - , so:
const subtractor = (a, b) => a - b
const summator = (a, b) => a + b
whateverArray.reduce(subtractor) === whateverArray.reduce(subtractor, whateverArray[0])
whateverArray.reduce(summator) === whateverArray.reduce(summator, 0)
I think as we needed to assign array to singleVal we had to switch the around from singleVal=array to array=singleVal otherwise we would be assigning array to 0.
Hello everybody, I did this (please see below) and it worked, my logic was that I needed to find an array value and then assigned it to singleVal. But I would like to know how or why it worked, sorry if it is a dumb question but I don’t understand how you can use the same var name, thanks!
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
var array = array.reduce(function(array,singleVal){
return array + singleVal;},0);