Sum All Numbers in a Range - solved

Hello guys,

Here is my solution to this problem. Can this be less verbose?

function sumAll(arr) {
  //Sort array so smallest number starts from index 0;
  arr = arr.sort((a,b) => a - b);
  //iterate and sum all numbers;
  let sum = 0;
  for(let i = arr[0]; i <= arr[1]; i++){
    sum += i;
  };
  //return sum of all numbers
  return sum;
};


There is a formular for how to calculate the sum of all numbers in a range, given just the first and last number.

Making an array only to sum the contents of the array is generally not a good idea. Making an array one element at a time with a loop like that is pretty slow, relatively speaking, and it’s it’s just not a best practice.

Thank you for your feedback. Please is there a reference material where I can get a full perspective on your contribution? It will help me study.

I’m not sure what you’re asking for? There isn’t a big list out there on absolute best practices that exist for every situation.

Or are you asking about the formula? That you can get by Googling ‘sum in range formula’.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.