If the order does not matter you can use the following:
const searchIn = [
["pik13", "karo10"],
["karo14"],
["karo11"],
["karo6", "pik10"],
["herz10"],
["pik11", "kreuz10", "kreuz11"],
];
const searchFor = ["pik11", "kreuz10", "kreuz11"];
/**
* Check if the the elements in an array matches the elements in the Set
* @param {Array} array
* @param {Set} toBeFound
* @returns
*/
function compareArray(array, toBeFound) {
// early outs it the element is not an array or the length does not match
if (!Array.isArray(array) || array.length !== toBeFound.size) return false;
// finds match in O(n) due fast lookup in Set
return array.every((item) => toBeFound.has(item));
}
/**
* Search for array in array.
* @param {Array} toBeSearched
* @param {Array} toBeFound
* @returns
*/
function searchForArray(toBeSearched, toBeFound) {
// use a set to make the lookups faster => O(1)
const elements = new Set(toBeFound);
return toBeSearched.findIndex((array) => compareArray(array, elements));
}
console.log(searchForArray(searchIn, searchFor));
This uses a
Set to speed up the lookup when comparing array values to
O(1) in contrast to using
includes() which will result in a worst case lookup runtime of
O(n). By reason of this the worst case runtime for
compareArray() is
O(n) instead of
O(n²). In most cases it will even be significantly faster as for instance in your example there is only one array which matches in length with the array we search for, so that we only compare the array values once. Overall in worst case the algorithm will take
O(m * n) where
m is the number of arrays to search and
n is the number of elements in the array we are looking for.
This will not work if you search for nested arrays, but can made to work with some changes for deep comparisons.