Sum All Numbers in a Range again

Tell us what’s happening:

So far I’ve got it to add up correctly if the start number in the array is lower than the end number but if the start number is higher than the end it doesn’t work.

I thought I could test for the start being higher than the end with if (start < end) {…} if (start > end) {…} but it doesn’t work.

The log seems to be pulling the right array.

I’m using reduce() to add up the numbers in the array.

Your code so far

function sumAll(arr) {
  
  var start = arr[0];
  var end = arr[1];
  
  var reducer = function (accumulator, currentValue) { 
    return accumulator + currentValue;
  };

  if (start<end) {
      myArr = [];
      for (var i=start; i<=end; i++) {

        myArr.push(i);

      }

    console.log(myArr);
    
  
    return myArr.reduce(reducer);

  }
  
   if (start>end) {
      var myArrDown = [];  
      for (var j=end; j>start; j--) {

        myArrDown.push(j);

      }

    console.log(myArrDown);
  
    return myArrDown.reduce(reducer);

  }
  

}

sumAll([1, 4]);

// sumAll([4, 1]);

Your browser information:

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

Link to the challenge:
https://www.freecodecamp.org/challenges/sum-all-numbers-in-a-range

In the second case, isn’t end supposed to be smaller than start? Then the condition in that for-loop is immediately false, because j starts with a value smaller than start.

I’m such an idiot.

So all I needed to do was reverse the variables in the for loop!

  if (start>end) {
      var myArrDown = [];  
      for (var j=start; j>=end; j--) {

It works now yay!