Danish February 2016

Function to add up all the numbers from 1 to num

I think there could be a better version then my solution. My Solution is working just fine. I didn't like juggling of all values using for loop.

But I am particularly wondering, If there is nice and one line solution getting all values in array up to entered number from function.

function SimpleAdding(num) {
  var Fnum = [];
  for (var i = 1; i <= num; i++) {
    Fnum.push(i);
  }
  return Fnum.reduce(function(prevValue, currentValue) {
    return prevValue + currentValue;
  })
}

Answers


gurvinder372 February 2016

I think there could be a better version then my solution.

use this formula

function SimpleAdding(num) {
    return num * (num+1) /2;
}

If there is nice and one line solution getting all values in array up to entered number from function

function SimpleAdding(num) {
  var Fnum = new Array(num).join().split(',').map(function(item, index){ return ++index;});

  return Fnum.reduce(function(prevValue, currentValue) {
    return prevValue + currentValue;
  })
}


Tushar February 2016

You can use Array#fill with Array#reduce

Array(num) // [undefined x num]
    .fill(0) // Array of `num` zeros
    .reduce((prev, curr, ind) => prev + (ind + 1), 0); // (ind + 1) is the number

var num = 10;
var sum = Array(num).fill(0).reduce((prev, curr, ind) => prev + (ind + 1), 0);

console.log(sum);
document.body.innerHTML = sum;

  1. Create an array of n elements using Array()
  2. Fill the array by zeros, using .fill
  3. To get the sum of elements use .reduce whose third parameter is the index. As index is zero-based, adding 1 to it will give the numbers from 1 to n.


Nina Scholz February 2016

You can, for a nice and one line solution getting all values in array up to entered number from function, use Array.apply() and Array.prototype.map().

var array = Array.apply(null, { length: 10 }).map(function (_, i) { return i + 1; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Post Status

Asked in February 2016
Viewed 1,368 times
Voted 11
Answered 3 times

Search




Leave an answer