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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
juanli
  • 583
  • 2
  • 7
  • 19

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
  • 58,414
  • 16
  • 114
  • 157
Berendschot
  • 3,026
  • 1
  • 21
  • 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
  • 8,059
  • 6
  • 35
  • 43
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);
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52