2

I have an function that takes an array as an input. How can I modify it to work with variable arguments as well as arrays. For example I want arrSum(1,2,3) === arrSum([1,2,3]) to return true i.e. both should return 6

const arrSum = arr => arr.reduce((a,b) => a+b,0)
console.log(arrSum([1,2,3]))
JJJ
  • 32,902
  • 20
  • 89
  • 102
Rohit Kumar
  • 19
  • 2
  • 7
  • Use the `arguments` variable. – Miquel Al. Vicens Dec 22 '17 at 13:03
  • 3
    FWIW, I would advice against designing the API to be *that* flexible. Accepting a variable number of arguments, fine. Accepting an array, fine. Accepting *either*? No. I'd go with the variadic function, and if you ever have an array of values it's easy enough to apply that using the spread operator or `arrSum.apply(null, arr)`. – deceze Dec 22 '17 at 13:03

3 Answers3

10

You can use spread syntax with concat. In first case you will get array with another array inside and in second case just an array of arguments but with [].concat(...arr) you will transform that to array of arguments for both cases.

const arrSum = (...arr) => [].concat(...arr).reduce((a, b) => a + b, 0)
console.log(arrSum([1, 2, 3]))
console.log(arrSum(1, 2, 3))
console.log(arrSum([1, 2, 3], [4], 5))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

You can solve this problems in many way , one way if you're using arrow function would be like this using rest operator

const arrSum = (...arr) => {
    // if we have just on param which is array
    if (arr.length === 1) {
        return arr[0].reduce((a, b) => a + b, 0);
    }
    return arr.reduce((a, b) => a + b, 0);
};
console.log(arrSum(1, 2, 3)); // 6
console.log(arrSum([1, 2, 3])); // 6

in the code above we use rest operator learn more rest_parameters MDN

also we can use normal functions using the variable arguments inside functions like this

function arrSum(args) {
 
    if (arguments.length === 1) {
        return arguments[0].reduce((a, b) => a + b, 0);
    } else {
        return [].reduce.call(arguments, (a, b) => a + b, 0);
    }
}
console.log(arrSum(1, 2, 3));
console.log(arrSum([1, 2, 3]));

learn more about
arguments Object MDN

US/docs/Web/JavaScript/Reference/Functions/arguments

so the same problem can be solved many ways choose what works best for you .

mostafa tourad
  • 4,308
  • 1
  • 12
  • 21
0

A solution example:

function arrSum( nums ) {
  var n = 0;
  if ( typeof( nums ) != 'object' )
    return arrSum( arguments );
  for ( var i = 0; i < nums.length ; i++ )
    n += nums[ i ];
  return n;
}

arrSum( 1, 2, 3 );
arrSum( [ 1, 2, 3 ] );