Tell us what’s happening:
Hello,
I am at this stage i read the description, but unfortunalty i didn’t understand the content, so i decided to ask for help to see if there is someone who would be able to better explain the content of this task.
Your code so far
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
singleVal = array.reduce(function(){
return singleVal +=
});
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.
array.reduce is a method that loops into an array, apply a callback function to each elements until reduce (hence the name) the array to a single element.
Just to give you a real life scenario, imagine that I have an e-commerce app, and I want to give the total price to my user.
I have an array that holds all the values:
var partialPrices = [item1, item2, item3]
Now I want to write a function that will simply sum all the item prices and return a single value, I can use `reduce’ for this purpose:
var partialPrices = [12, 5, 10, 3]
var totalPrice = partialPrices.reduce(function(total, itemInTheArray) {
return total + itemInTheArray;
}, 0) // totalPrice === 30;
/** explanation */
The accumulator (in my function I decided to call it total) takes the return value of the last invocation callback function, and in this case is initialised to 0 thanks to the optional second argument of the reduce function.
So my reduce behave like this:
1) accumulator = 0 - currentValue =12 // accumulator is initialised to 0, first item in array is 12
2 ) accumulator = 12 - currentValue= 5 // (0 + 12) - second item in the array is 5
3) accumulator = 17 - currentValue = 10 // (12 + 5) - third item in the array is 10
[...]
until we finish the array