Got stuck on coding challenge

I got stuck on a coding challenge that is called All Star Code Challenge #20 on codewars.
I don’t understand something in instructions as below:

  • Raise an error if input arguments are not of equal length.

Here is the full instruction below:

Create a function called addArrays() that combines two arrays of equal length, summing each element of the first with the corresponding element in the second, returning the "combined" summed array.
Raise an error if input arguments are not of equal length.

Here is my code so far:

function addArrays(array1, array2) {
 let newArr = [];
  if (array1.length === array2.length) {
    for (let i = 0; i < array1.length; i++) {
      newArr.push(array1[i] + array2[i]);
    }
  
  return newArr;
  } else if (array1.length !== array2.length) {
    return 'Error';
  }
 
}

The link to challenge: https://www.codewars.com/kata/5865a75da5f19147370000c7/train/javascript
So what I need to do/fix on my code?

Hi,

I would add a guard clause that initially checks whether the arrays are of equal length and bails if that is not the case:

function addArrays(array1, array2) {
  if(array1.length !== array2.length) throw new Error('Arrays not equal length');
}

Then, if that doesn’t trigger, you know you are good to do the addition:

function addArrays(array1, array2) {
  if(array1.length !== array2.length) throw new Error('Arrays not equal length');
  
  return array1.map((el, i) => el + array2[i]);
}

I would also encourage you to look at array methods such as map, filter etc, as opposed to using loops.

This podcast episode does a good job of explaining them.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.