I am really new at learning JavaScript and I am completing some exercises from the Odin Project. I am stuck at one part of the calculator that should sum all the arguments, but the output changes if you use an array to call the function. My code is the following:
const sum = function(...numbers) {
let result = 0;
for (let each of numbers){
result += each};
return result;
};
It works perfect if I call the function like so:
sum(7,11)
and it returns 18
However, one of the checks is that it needs to enter the arguments as an array:
test('computes the sum of an array of two numbers', () => { expect(calculator.sum([7,11])).toBe(18);
So when it calls the function like this sum([7,11])
it returns 07,11
and also returns it as a string, so it does not pass this check. I am pretty sure the solution may be simple but I am not able to find what the issue is.
const sum = function(...numbers) {
let result = 0;
for (let each of numbers){
result += each};
return result;
};
console.log(sum(7,11))
console.log(sum([7,11]))
You can force an array
const sum = (...numbers) => [numbers].flat(Infinity).reduce((a,b)=> a+b)
console.log(sum(7,11))
console.log(sum([7,11]))
console.log(sum([7,11],[21,50]))