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){
    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?


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[0];
var b = arr[1];
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[0]; i < arr[1] + 1; i++) {
  return numRange.reduce(function(prev, curr) {
    return prev + curr;

Notice the difference - we’re creating a new array that contains all numbers between arr[0] and arr[1], 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

Thanks for replying.
It helped me a lot.