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 .