Sum All Numbers in a Range not accepting answer

Sum All Numbers in a Range not accepting answer
0

#1

Tell us what’s happening:
I am getting the correct return value for each test but FCC isn’t accepting it
Im not sure if it’s because my code is so messy or what.

Your code so far

function sumAll(arr) {
  var max = arr.reduce(function(a, b) {
    return Math.max(a, b);
  });

  var min = arr.reduce(function(a, b) {
    return Math.min(a, b);
  });

  var result;
  for (var i = min; i <= max; i++) {
    newArr.push([i]);
  }
  var flat = newArr.reduce(function (a, b) {
    return a.concat(b);
  });
  var sum = flat.reduce(function (a, b) {
    return a + b;
  }, 0);
  return sum;
}

sumAll([5, 10]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36.

Link to the challenge:


#2

Your code does not run, because of the Reference Error showing in the console.

ReferenceError: newArr is not defined

When you try to do:

  for (var i = min; i <= max; i++) {
    newArr.push([i]);
  }

since newArr does not exist, you can not push any data to it.

EDIT: Also, why are you using reduce to get the min and max?

  var max = arr.reduce(function(a, b) {
    return Math.max(a, b);
  });

  var min = arr.reduce(function(a, b) {
    return Math.min(a, b);
  });

Why not just use the following?

var max = Math.max(arr[0],arr[1]);
var min = Math.max(arr[0], arr[1]);

There are other more advanced ways, but the above approach is not overly complicated.


#3

How is:

var max = Math.max(...arr);
var min = Math.max(...arr);

more advanced, than your code? As to me it seems simpler.

Why do you making array of arrays, then flatten it? If you don’t need that you could push just number:

arr.push(i) // instead of arr.push([i])

You can also square whole range, then compute square root out of it.


#4

@0Prime - More advanced than has been introduced to the campers following the map up to this point. The spread syntax (…) is not mentioned in the current FCC curriculum, so it may appear to a new camper as advanced. That is all I meant.