Condense arrays with reduce challenge

Condense arrays with reduce challenge
0

#1

Tell us what’s happening:

Cant see the problem with this piece of code. Please help.

Your code so far

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

// Only change code below this line.

singleVal = array.reduce(function(array){
  for (var i = 0; i < array.length; i++){
    singleVal += array[i];
  }return singleVal;
} );

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; rv:54.0) Gecko/20100101 Firefox/54.0.

Link to the challenge:


#2

You need to understand how array.reduce() works in order to see the problem with your code. (don’t worry it’s tough to get your head around it if it’s the first time you see it).

Let’s try an example.

var array = [1, 2, 3, 5];
var initialValue = 0;

// Sum all numbers in the array
var sum = array.reduce(function (currentSum, currentValue) {
 return currentSum + currentValue;
}, initialValue);

console.log(sum); //outputs 11

The callback inside array.reduce() will run 4 times, as many as our elements. Each time it runs, currentValue will contain one of the elements (so the first time it has 1 then 2, etc). Now, currentSum hold the value that you returned from the previous callback (the first time, it takes the value of initialValue). Here’s the values for each iteration

// #1
// currentSum: 0 (remember the first time it has the value of initialValue)
// currentValue: 1 (the first array element)
// #2
// currentSum: 1 (what we returned in #1)
// currentValue: 2 (the second array element)
// #3
// currentSum: 3 (what we returned in #2)
// currentValue: 3 (the third array element)
// #4
// currentSum: 6 (what we returned in #3)
// currentValue: 5 (the fourth array element)

// sum:11

So, what essentially happens in your code, is that the first time the callback runs, it returns the actual sum and in the second iteration your array is no longer an array but it’s a number (the sum).

// #1
// array: [4,5,6,7,8]
// #2
// array: 30
// ! error ! array.length is undefined 

I am not the best at passing through knowledge so if there is something you don’t understand let me know and I’ll do my best to explain it better.


#3

You are very clear. Thanks a bunch…