We're a place where coders share, stay up-to-date and grow their careers.

On your solution, you may change the original array destructively.

const arr = [5, 0] sumAll(arr) // 15 arr // [ 0, 5 ]

To avoid this, you can use [...arr] or concat() method.

function sumAll(arr) { arr = [...arr] let fullArr = []; arr.sort((a,b) => a - b); for (let i = arr[0]; i <= arr[1]; i++) { fullArr.push(i); } let sum = fullArr.reduce((acc, currVal) => {return acc + currVal}, 0); return sum; } const arr = [5, 0] sumAll(arr) // 15 arr // [ 5, 0 ]

And, my trials here:

const sumAll = ([a, b]) => closedRange(a, b) .reduce( (acc, e) => acc + e , 0 ) const closedRange = (a, b) => a > b ? [...Array(a - b + 1).keys()] .map(e => a - e ) : [...Array(b - a + 1).keys()] .map( e => a + e )

Or, more simply:

const sumAll = ([a, b]) => (a + b) * (Math.abs(a - b) + 1) / 2

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.

Hide child comments as well

Confirm

For further actions, you may consider blocking this person and/or reporting abuse

On your solution, you may change the original array destructively.

To avoid this, you can use [...arr] or concat() method.

And, my trials here:

Or, more simply: