juanli
juanli

Reputation: 613

Cannot read property 'includes' of undefined for JavaScript Array object

Here are my code:

var nestedArr = [[1, 2, 3], [5, 2, 1, 4]];
var result;

  for (var a = 0; a < nestedArr.length; a++) { // iterate nestedArr
    for (var b = 0; b < nestedArr[a].length; b++) {
      if (nestedArr[a+1].includes(nestedArr[a][b])) {
        result.push(nestedArr[a][b]);
    }
  }
}

Output: Error: Cannot read property 'includes' of undefined. But at least I can make sure several things: 1. includes() method exists for array in JavaScript 2. Run a single statement nestedArr[a+1]; in console give me the array [5, 2, 1, 4]

So, I really don't understand the Error? Please help me figure out this. Thanks.

Upvotes: 0

Views: 6373

Answers (3)

Berendschot
Berendschot

Reputation: 3104

The program will search for an index that doesn't exist.

var nestedArr = [[1, 2, 3], [5, 2, 1, 4]];
  ...
    ...
      if (nestedArr[a+1].includes(nestedArr[a][b])) {
      // As nestedArr.length will return 2, the program will eventually  search for nestedArr[2+1 (=3)] which doesn't exist.
    }
  }
}

Bonus: Why not use for var i in nestedArr instead of using .length

Take a look at this answer.

Upvotes: 1

Jack jdeoel
Jack jdeoel

Reputation: 4584

As @Nina Scholz commented

the last index plus one does not exist

You don't need to check by includes ! Just do loop and assign using filter and map as example !!!

var nestedArr = [[1, 2, 3], [5, 2, 1, 4]];
    var result = [];
    nestedArr.filter( (val) => {
      val.map( (v) => { result.push(v); } )
    })
    console.log(result);

Upvotes: 0

Naramsim
Naramsim

Reputation: 8732

var nestedArr = [[1, 2, 3], [5, 2, 1, 4]];
var result = [];

  for (var a = 0; a < nestedArr.length; a++) { // iterate nestedArr
    for (var b = 0; b < nestedArr[a].length; b++) {
      if (nestedArr[a].includes(nestedArr[a][b])) {
        result.push(nestedArr[a][b]);
    }
  }
}
console.log(result)

removing the plus one did the job, basically you tried to access an array were no arrays were present

Upvotes: 1

Related Questions