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

Time:12-02

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

Thanks

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Another approach transform the inner-arrays of array into strings like ['1,2,3', '2,2,2', '3,2,1'] and also transform the matching array into string 2,2,2. then use built-in function indexOf to search of that index in array.

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

const arr1Str = arr1.map(innerArr=>innerArr.toString());
const index = arr1Str.indexOf(match.toString())
console.log(index);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related