# Condense arrays with reduce-Need help

Condense arrays with reduce-Need help
0

#1

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.

var array = [4,5,6,7,8];
var singleVal = 0;

// Only change code below this line.

singleVal = array.reduce(function(){
return singleVal +=
});

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.

#2

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) {
}, 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

Make sense?
Hope it helps

#3

thank you for your kind help now it make sense to me i will try to do the exact task and see if i can practise the way i understood it
thank you a lot

#4

Thank you. I completely understand it now. Your explanation was really clear and very helpful. Great job!

#5