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.

2
  • 6
    the last index plus one does not exist. Commented Feb 9, 2018 at 9:59
  • What does this code intend to achieve? Commented Feb 9, 2018 at 10:00

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.