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
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.
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.