Sum All Numbers in a Range

xmohammedawad

Mohammed Awad

Posted on May 10, 2023

Sum All Numbers in a Range

DESCRIPTION:

We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first.

Examples

sumAll([1, 4]) `should return 10`.

sumAll([10, 5]) `should return 45`.
Enter fullscreen mode Exit fullscreen mode

My approach for solving this problem:

  • find the min and max value in the array.
  • fill the array with range from min to max.
  • if not return sliced str with num length.
  • get the summation of the array with reduce().

My solution:

function sumAll(arr) {
  const minNumber = Math.min(...arr);
  const maxNumber = Math.max(...arr);
  return new Array(maxNumber - minNumber + 1)
  .fill()
  .map((num,index)=> minNumber+index)
  .reduce((perv,num) => perv + num)
}

sumAll([1, 4]);
Enter fullscreen mode Exit fullscreen mode

Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!

Follow Muhmmad Awd on

If you have any questions or feedback, please feel free to contact me at

💖 💪 🙅 🚩
xmohammedawad
Mohammed Awad

Posted on May 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Sum All Numbers in a Range
webdev Sum All Numbers in a Range

May 10, 2023