# Help with sum-all-numbers-in-range

Hi Everybody,
for this problem,
the question asked to solve with help of reduce function.

My solution is

``````function sumAll(arr) {

var ans= arr.reduce(function(a,b){
numb=Math.abs(a-b);
return 0.5*(a+b)*(numb+1);

});

return ans;

}

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

I used a math formula here, is there some other intelligent solution with reduce function?

Thanks

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

I also changed your title to reflect your question.

You don’t need to use `reduce` with that forumla. Your function can simply return the result of the calculation:

function sumAll(arr) {
var a = arr;
var b = arr;
return 0.5 * (a + b) * (Math.abs(a - b));

`reduce` is great for working with arrays of data, and it could be used to solve the problem this way:

``````function sumAll(arr) {
var numRange = [];
for(var i = arr; i < arr + 1; i++) {
numRange.push(i);
}
return numRange.reduce(function(prev, curr) {
return prev + curr;
},0);
}
``````

Notice the difference - we’re creating a new array that contains all numbers between `arr` and `arr`, then iterating through the array. I think it’s better to use the simple formula, but you should try writing out the version with `reduce` as that is a very important array method to know.

1 Like