在另一个数组

时间:2017-09-09 17:39:57

标签: javascript arrays

我正在处理阵列数组'并试图测试是否所有'设置'包含在第二个数组中的数据存在于第一个数组中。

var arr = [['Netherlands','PP3a'],['Austria','PP16a'],['Estonia','PP3a'],['Luxembourg','PP3a'],['Belgium','PP3a']];

var n   = [['Luxembourg','PP3a'],['Netherlands','PP3a'],['Belgium','PP3a']];

在我的示例https://jsfiddle.net/mnb8jddw/中,它们显然存在,但代码(偶然似乎与数字一起使用)读取错误。我显然感到困惑,并且非常感谢一些帮助,因为我怀疑我采取了错误的做法。

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

1 个答案:

答案 0 :(得分:1)

我不确定这是你正在寻找的答案,但如果你正在寻找一个快速而肮脏的解决方案,你可以尝试这样的事情:

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

请注意元素的顺序很重要(例如:['Luxembourg', 'PP3a']将匹配,但['PP3a', 'Luxembourg']不会匹配)

请参阅updated fiddle