Search code examples
javascriptarraysecmascript-6

How to see if an array includes a nested array with specific values?


How to correctly iterate through shipMisses array to see if it contains the nested array with the specific values [2, 4] (the dName variabe)?

Here is my code:

shipMisses.includes(dName) // shipMisses = [[0, 1], [2, 4]]
                           // dName = [2, 4]

Solution

  • You can use the callback function for comparison. Here is an example:

    const shipMisses = [[0, 1], [2, 4]];
    const dName = [2, 4];
    
    // Using Array.prototype.some() to iterate and check if any array matches dName
    const containsDName = shipMisses.some(arr => arr[0] === dName[0] && arr[1] === dName[1]);
    
    console.log(containsDName); // true