4

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

2 Answers 2

5

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

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

1 Comment

Ah perfect, that's the combo I'm after. Thanks!
0

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

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.