Alice Jarmusch
Alice Jarmusch

Reputation: 477

Create a function that will convert a parameter to array

I need to create a function, that will parse function parameter of integer to an array list.

So if we call the function like this: sum(1, 4 ,7); then inside of the function 'sum' the arguments variable/keyword will look like this [1, 4, 7]. I need to create a sum function so that it can take any number of arguments and return the sum of all of them.

Here's my code so far:

function sum ([a,b]) {
var arr = [a,b];
var sum =arr.reduce(add, 0);

function add(a, b) {
return a + b;
}
}

I also was trying to so something like this:

function sum ({
  arr[0]: 1;
  arr[1]: 2;
  arr[2]:3;

  var sum =arr.reduce(add, 0);

function add(a, b) {
return a + b;
}
})

but I obviously doing something wrong.

Upvotes: 1

Views: 89

Answers (4)

Lewis
Lewis

Reputation: 14866

Try this ES6 solution.

let sum = (...args) => args.reduce((a, b) => a + b, 0);

You can see the MDN article of rest parameters for more details. It is basically used for retrieving the list of arguments in an array.

Upvotes: 0

Vijayraj
Vijayraj

Reputation: 193

var sum =function() {
    var args = [];
    args.push.apply(args, arguments);
    return args.reduce((a,b) => { return a+b}, 0); // ES6 arrow function
}
sum(1,2,3); // return 6

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

Just for changing arguments to an array of an array like object, you could use Array.apply.

Read more:

function x() {
    return Array.apply(Array, arguments);
}

var array = x(1, 4, 7);

console.log(array);
console.log(typeof array);
console.log(Array.isArray(array));

Upvotes: 0

tomision
tomision

Reputation: 994

Try this

function sun () {
  return Array.prototype.reduce.call(arguments, function(pre, cur) {
    return pre + cur
  }, 0)
}

This is your need.

Upvotes: 2

Related Questions