TypeError: newArr.includes is not a function


#1

I’m having a problem with my code. Whenever I run .includes() on my array, it says that it’s not a function.

function uniteUnique(arr) {
  var newArr = [];
  for(x = 0; x < arr.length; x++) {  // loops for nested arrays
    for(y = 0; y < arr.length; y++) {
      if(!newArr.includes(arr[x][y])) {  // TypeError: newArr.includes is not a function
        newArr = newArr.push(arr[x][y]);
      }
    }
  }
  return newArr;
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

#2

.push() returns the new length of the array after pushing, not the array itself. You shouldn’t do newArr = newArr.push() because it will replace the array with a number (and so you get the error message, because numbers don’t have an .includes() function).

newArr.push(..); alone should do.


#3

Okay sweet, that worked, but now I have another problem. newArr is empty when I run the script.
Here’s the updated code:

function uniteUnique(arr) {
  var newArr = [];
  for(x = 0; x < arr.length; x++) {
    for(y = 0; y < arr[x].length; y++) {
      if(!newArr.includes(arr[x][y])) {
        newArr.push(arr[x][y]);
      }
    }
  }
  return newArr;
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

#4

Your input doesn’t look like an array of arrays. arr only captures the first array (the [1,3,2] array). The code fails because you’re trying to iterate over this array as if it was a matrix.

Here’s a few ways to fix it:

  • Use the arguments object. You can insert arr = [].slice.call(arguments); at the beginning of your code to capture all of the arguments passed in and put them all in one array. But arguments is already deprecated.
  • Modify your parameter list. You can change function uniteUnique(arr) to function uniteUnique(...arr), and that’s it. What ...arr does is it gathers all of the arguments passed in into one array.

Either way, you’re now iterating over an array of arrays, but I recommend the latter.


#5

Thanks, that helps a bunch!