skip to Main Content

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]

2

Answers


  1. 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
    
    
    Login or Signup to reply.
  2. You can use the Array#some element to check if at least one element is:

    • an array, and
    • equal to the given array (the JSON.stringify method is one way to check)
    const shipMisses = [[0, 1], [2, 4]];
    const dName = [2, 4];
    
    const arrayFound = shipMisses.some(
      a => 
      //check if the element is an array
      Array.isArray(a) 
      //and
      && 
      //check if it equals dName
      JSON.stringify(a) === JSON.stringify(dName)
    );
    
    console.log( arrayFound );

    Using the same array method you may also check by iteration to see if at least one element is:

    • an array, and
    • has the same length as the given array, and
    • every element of this array equals the corresponding element in the given array
    const shipMisses = [[0, 1], [2, 4], [6, 8, 0, 9]];
    const dName = [6, 8, 0, 9];
    
    const arrayFound = shipMisses.some(
      a => 
      //check if the element is an array
      Array.isArray(a) 
      //and
      && 
      //check if lengths are equal
      a.length === dName.length
      //add
      &&
      //check if each element of a equals the corresponding element of dName
      a.every((b,i) => b === dName[i])
    );
    
    console.log( arrayFound );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search