# Sum All Numbers in a Range-[insight]

Sum All Numbers in a Range-[insight]
0

#1

Tell us what’s happening:
Step1: I first sort the array to fetch the min(1st elem) and the max(last elem) of the array
Step2: I then traverse through the 1st and the Last(min & max) to get all the numbers pushed to a new array
Step3: perform a reduce method to get the sum of all the elements in the new array.

Can I consider this as the good method for solving this problem?

Your code so far

``````function sumAll(arr) {
arr.sort(function(a,b){
return a-b;
});
arr1=[];
for(var i=arr[0];i<=arr[arr.length-1];i++){
arr1.push(i);
}

return arr1.reduce(function(prev,curr){
return prev+curr;
});
}

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

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

Link to the challenge:

#2

Your logic is nice and clear, and is a good approach. If there’s one thing I’d point out (though not logic-related), the `arr1` variable should have been declared with `const` or `var` keyword (i.e., `const arr1 = [];`). This makes sure that the variable is declared in the scope of the function, not the global scope.

#3

You solution does work fine.

However, instead of creating an extra array to store the numbers, why not just create a variable (call it sum and initialize it to zero) and then add the value of i to it during each iteration of the for loop? Then you would not need to create the extra memory needed for the array and you would not have to iterate through an array using reduce, because the addition would happen inside the first for loop.