Puedo encontrar si existe una matriz en otra matriz:
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; }); });Y puedo encontrar el índice de esa matriz:
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; } }Pero, ¿es posible encontrar el índice usando las funciones de orden superior de JS? No pude ver una pregunta/respuesta similar, y es solo un poco más clara en cuanto a la sintaxis.
Gracias
Podrías tomar 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);Otro enfoque transforma las inner-arrays de la matriz en cadenas como ['1,2,3', '2,2,2', '3,2,1'] y también transforma la matriz coincidente en la cadena 2,2,2 . luego use la función indexOf para buscar ese índice en la matriz.
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);