0

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.

Flimzy
  • 68,325
  • 15
  • 126
  • 165
juanli
  • 545
  • 2
  • 7
  • 16

3 Answers3

1

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.

isherwood
  • 52,576
  • 15
  • 105
  • 143
Berendschot
  • 2,944
  • 1
  • 20
  • 43
1
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

Naramsim
  • 7,003
  • 4
  • 34
  • 42
0

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);
David Jaw Hpan
  • 4,511
  • 3
  • 24
  • 50