Condense arrays with reduce: Challenge number 224

Tell us what’s happening:

Your code so far

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

// Only change code below this line.

singleVal = array.reduce(function(singleVal, array){
  for(var i = 0; i < array.length; i++){
    singleVal += array[i];
  return singleVal
Can anyone tell what is wrong with this code???

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36.

Link to the challenge:

The Array.prototype.reduce function already adds all the items together within the function. THere is no need for the for loop.
All you have to do is:

var singleVal;

singleVal = array.reduce(function(acc, curr ){
  return acc + curr;
1 Like

You do not need a for loop inside your reduce callback function, because reduce already iterates over the array. You do not seem to understand what the callback arguments represent. The first argument represents the accumulator (what will eventually hold your sum). The second argument represents the current element being iterated over in the array.

Maybe, if you removed the for loop and changed the name of the 2nd argument to element, it might help you visualize what you need to do. See below for a modified (but not the actual solution of what you started):

singleVal = array.reduce(function(singleVal, element){
    return something + somethingElse

The something and somethingElse represent other variable names which you should actually use.

EDIT: Someone else already gave you the solution as I was typing this message. I was trying to get you to figure it out on your own instead of just giving it to you.

1 Like