Reputation: 477
I'm dealing with 'arrays of arrays' and trying to test if all 'sets' contained in the second array are present in the first array.
var arr = [['Netherlands','PP3a'],['Austria','PP16a'],['Estonia','PP3a'],['Luxembourg','PP3a'],['Belgium','PP3a']];
var n = [['Luxembourg','PP3a'],['Netherlands','PP3a'],['Belgium','PP3a']];
In my example https://jsfiddle.net/mnb8jddw/ they clearly are present, but the code (which incidentally seems to work with numbers), reads false. I've obviously got myself confused and would really appreciate some help as I suspect I'm taking the wrong approach.
var arr = [
['Netherlands', 'PP3a'],
['Austria', 'PP16a'],
['Estonia', 'PP3a'],
['Luxembourg', 'PP3a'],
['Belgium', 'PP3a']
];
var n = [
['Luxembourg', 'PP3a'],
['Netherlands', 'PP3a'],
['Belgium', 'PP3a']
];
function searchForArray(haystack, needle) {
var i, j, current;
for (var i in haystack) {
if (needle.length === haystack[i].length) {
current = haystack[i];
for (j = 0; j < needle.length && needle[j] === current[j]; ++j);
if (j === needle.length)
return i;
}
}
return -1;
}
console.log(searchForArray(arr, n)); // -1 = false
Upvotes: 0
Views: 32
Reputation: 2801
I'm not sure that it is the answer you are looking for, but if you are looking for a quick and dirty solution, you could try something like this:
const lookup = (ar, sets) => {
// concatenate each entry in the searched array
const _hashed = ar.map(i => i.join(''))
return sets.every((set) => {
// contatenate each entry to look for
const _set = set.join('')
// does the searched array contain the concatenated string?
return _hashed.indexOf(_set) > -1
})
}
console.log(lookup(arr, n)) // => true
Note that the order of the elements matters (ie: ['Luxembourg', 'PP3a']
will match, but ['PP3a', 'Luxembourg']
won't)
See updated fiddle
Upvotes: 1