0

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
2
  • According to the code, the needle should be one subelement of n. For eg, searchForArray(arr,n[0]); would returns 3. Commented Sep 9, 2017 at 17:46
  • what index your function should return? the elements you search do not exist in that order Commented Sep 9, 2017 at 18:03

1 Answer 1

1

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

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

2 Comments

I'm really not sure why you call this 'Q&D'. It does the job brilliantly and I much appreciate your help!
Q&D because map and every methods are not really optimized for speed, and, as stated, it won't fit every use cases. You may consider sorting the strings (.sort((a, b) => a.localeCompare(b))) if order matters!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.