Condense arrays with reduce-Need help

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.

Link to the challenge:
https://www.freecodecamp.org/challenges/condense-arrays-with-reduce

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

Make sense?
Hope it helps :slight_smile:

4 Likes

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

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

Glad you found it useful.
It’s always good to have reduce ready in your coding belt.
Happy coding :space_invader:

1 Like

In the question that op mention it doesn’t declare the initial value like u did in ur example, if it doesn’t declare we can assume it is 0?

If no initialValue is provided reduce uses the first element of the array; throws an error if the array is empty.

You can read all about it on the mdn documentation