Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the index of an array in an array using higher order functions?

I can find whether an array exists in another array:

const arr1 = [[1,2,3],[2,2,2],[3,2,1]];

const match = [2,2,2];

// Does match exist
const exists = arr1.some(item => {
  return item.every((num, index) => {
    return match[index] === num;
  });
});

And I can find the index of that array:

let index;
// Index of match
for(let x = 0; x < arr1.length; x++) {
  let result;
  for(let y = 0; y < arr1[x].length; y++) {
    if(arr1[x][y] === match[y]) { 
      result = true; 
    } else { 
      result = false; 
      break; 
    }
  }
  
  if(result === true) { 
    index = x; 
    break;
  }
}

But is it possible to find the index using JS’ higher order functions? I couldn’t see a similar question/answer, and it’s just a bit cleaner syntax wise

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

You could take Array#findIndex.

const
    array = [[1, 2, 3], [2, 2, 2], [3, 2, 1]],
    match = [2, 2, 2],
    index = array.findIndex(inner => inner.every((v, i) => match[i] === v));

console.log(index);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading