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