Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calculator exercise is not returning the correct output

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]))

>Solution :

The reason is that ...numbers means for array,and you have passing parameters like [7,11],so it’s a nested array,in this case,you need to use numbers[0] instead

You can reference to how-to-check-if-array-is-multidimensional-jquery to get more detail information of it.

const sum = function(...numbers) {
  let result = 0;
  let isSubArray = Array.isArray(numbers[0]);
  let data = isSubArray ? numbers[0]:numbers;
  for (let each of data){
    result += each
  };
  return result;
};
console.log(sum([7,11]))
console.log(sum(7,11))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading