# Intermediate Algorithm Scripting: Sum All Numbers in a Range_Help Requested

Hello. My reduce function doesn’t seem to be working. Could you tell me what I’m doing wrong? Thanks in advance!

``````function sumAll(arr) {
let arrSorted = arr.sort(function(a,b) {return a - b});
console.log(arrSorted)
let newArr = [];
let plusOne = 1;
let i = 0
newArr.push(arrSorted[0]);
while (plusOne < arrSorted[1]) {
newArr.push(arrSorted[0] + plusOne);
plusOne++;
}
newArr.push(arrSorted[-1]);
console.log(newArr);
return newArr.reduce(function(a,b){
return a + b;
});
}

sumAll([1, 4]);
``````

Sure. If you take a look at the console, your `newArr` for the first example ([1, 4]) is logging as `[1, 2, 3, 4, undefined]` – and adding `undefined` in your reduce function seems to be returning `NaN` (or a “not a number” error).

In order to debug this, I changed the last line (where you `return newArr.reduce(...)`), and broke it apart:

``````let returnValue = newArr.reduce(...);
console.log(returnValue);
return(returnValue);

``````

This allowed me to see what you’re actually returning. In this case, you’re returning “NaN”.

Out of curiousity, what do you think the following line does in your code?

``  newArr.push(arrSorted[-1]);``

I thought it might return the item at index 2. I got rid of it and fixed my while loop. This seemed to work.

``````function sumAll(arr) {
let arrSorted = arr.sort(function(a,b) {return a - b});
console.log(arrSorted)
let newArr = [];
let plusOne = 0;
while (arrSorted[0] + plusOne <= arrSorted[1]) {
newArr.push(arrSorted[0] + plusOne);
plusOne++;
}
console.log(newArr);
return newArr.reduce(function(a,b){
return a + b;
});
}

sumAll([5, 10]);
``````

little convoluted, maybe, but it looks good! well done.