# 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?

``````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`.

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.