Am I making use of reduce properly?

Tell us what’s happening:
I was just working on this challenge and it seems like it was pretty easy to solve however I am concerned that I am not making use of reduce properly in my code. Can someone please let me know if I am using reduce correctly? Or if I am using it when I could be using something else.

  **Your code so far**

function sumAll(arr) 
{
//sort array least to greatest
arr.sort((a,b)=>{return a===b?0:a>b?1:-1});


//add numbers between 2 values in arr
return arr.reduce((a,b)=>
{
  let sum=0
  for(;a<=b;a++)
  {
    sum+=a;
  }
  return sum;
});
}

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

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0

Challenge: Sum All Numbers in a Range

Link to the challenge:

It works, but no, that’s not a place where I would use a reduce, and that is not how I would use a reduce either.

That’s also definitely not how I would write a for loop.

You could solve this with reduce. If you created an array with the full range of numbers (not just the min and max), then you could use reduce to sum them. I’m not saying that is the best way to do it, but it could work.

3 Likes

Thank you Jeremy and Kevin. I am still trying to understand reduce (I got a hang of map and filter for now). I will redo the problem as I do not want to use reduce incorrectly.

Yeah, a lot of people get hung up on reduce. I once had to explain it to a senior dev. Just keep at it, you’ll get there.

2 Likes

If only JS had a range function…

To give you an example of what Kevin’s saying, you could create a function to produce all the numbers in a range as an array.

function range(start, stop) {
  const arr = [];
  for (let i = start; i <= stop; i++) {
    arr.push(i);
  }
  return arr;
}

Then using that you could reduce it down to a sum (solution spoiler):

function sumAll(arr) {
  const start = Math.min(...arr);
  const stop = Math.max(...arr);
  const sum = (a, b) => a + b;
  
  return range(start, stop).reduce(sum);
}
2 Likes

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