0

I have a function called sum this function should return the sum of sequential numbers for instance, if I gave the sum number 5 it should returns 1 + 2 + 3 + 4 + 5 = 15
i did it with forloop
but I'm wondering if it can be done with reduce() method in Javascript
this is my code

update with @Andrew Morton answer it was done like that.

//const sum = num => {
  //let newn = 0;
  //for(let i = 0; i <= num; i++) newn += i // 1+2+3+4+5=15
 // return newn;
//}  
//console.log(sum(5)); // 15 

 // Andrew solution
 const sum = num => {
   return (num * (num+1))/2;
  }
 console.log(sum(5));
Th1
  • 269
  • 2
  • 12
  • 6
    The sum of numbers from 1 to n is n(n+1)/2, if the aim is to make it shorter, faster, and simpler. – Andrew Morton Mar 02 '19 at 17:53
  • @AndrewMorton thank you, Andrew, that's exactly what I wanted ```n(n+1)/2``` – Th1 Mar 02 '19 at 21:49
  • Possible duplicate of [How to find the sum of all numbers between 1 and N using JavaScript](https://stackoverflow.com/questions/29549836/how-to-find-the-sum-of-all-numbers-between-1-and-n-using-javascript) – Andrew Morton Mar 02 '19 at 22:53

1 Answers1

2

You can use reduce if this is what you want:

const sum = num => {
    return Array.from(
        Array(num).keys(),
        key => key + 1
    ).reduce(
        (v1, v2) => v1 + v2
    )
}

BUT: The best way is to do it as Andrew Morton suggested it in comments:

The sum of numbers from 1 to n is n(n+1)/2, if the aim is to make it shorter, faster, and simpler. – Andrew Morton

Jakub Kosior
  • 186
  • 1
  • 2
  • 12