Going around my elbow to get to my thumb

I know I’m expending way too much effort this, but I can’t think of a simpler method right now.
I’d like to use something like a spread operator to obtain the numbers in between the first and last digits…is that at all possible?
Or is something like a range method possible. (I know something like that exists in lodash but for vanilla JS?)

Thanks, as always.
Nick
Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

function sumAll(arr) {
let sum = [];
let begin = parseInt(arr[0]);
let end = parseInt(arr[1]);
if(begin > end){
begin = parseInt(arr[1])
end = parseInt(arr[0])
}
for(let i = begin; i <= end; i++){
sum.push(i);
}
let result = sum.reduce((a,b)=>{return a+b})
console.log(result)
return result;
}

sumAll([1, 4]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

Challenge: Sum All Numbers in a Range

Link to the challenge:

let sum = [];
let begin = parseInt(arr[0]);
let end = parseInt(arr[1]);
if(begin > end){
  begin = parseInt(arr[1])
  end = parseInt(arr[0])
}

The input is an array of two integers, you don’t need to parse them to integers. And if you sort the input it will turn into sorted input, so as a hint

const [begin, end] = arr.sort(/* sort function here */)

There’s also no need to create an array of numbers then reduce it. You have the smallest and you have the largest so you can just loop and add numbers

Hello, I edited my code to make it (what I hope is more concise). I want to make sure I’m clear on the logic. Would someone mind looking at the explanation below as well as the code below and tell me if I’m off in some way?

Thanks so much for any help you can provide.

Nick

EXPLANATION:
1st Loop: i=1; i < 4; i +1
sum = 0+1 = 1, sum = 1;
2nd Loop: i = 1; i < 4; 1 + 1
1 + 2 = 3, sum = 3;
3rd Loop: i = 2; i < 4; 2+ 1;
3+ 3 = 6, sum = 6;
4th Loop: i = 3; 3 < 4; 3+1;
4+ 6 = 10, sum = 10;
return sum
CODE:

function sumAll(arr) {

   let sum = 0

arr = arr.sort((a,b)=> a-b);

let begin = arr[0];

let end = arr[1];

for(let i = begin; i <=end; i++){

  sum+=i;

}

return sum

}

sumAll([1, 4]);

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