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