根据javascript中的匹配条件从数组数组中查找匹配项

时间:2018-10-16 05:26:40

标签: javascript arrays

鉴于我有一个数组,如下所示:

var array = [["001"," 003"],["002"," 001"],["001"," 002"],["002"," 001"], ["", "001"]]

条件是数组必须相互匹配2个或更多,然后它将结果存储到新数组中。

我正在使用以下javascript方法,该方法将针对数组中的每个数组进行比较。

我要做的是使javascript方法不循环数组中的每个数组来查找匹配项,但这将基于上述条件(2个匹配项或更多)< / p>

JavaScript方法:

var array = [["001"," 003"],["002"," 001"],["001"," 002"],["002"," 001"], ["", "001"]]
console.log(
array.shift().reduce(function(res, v) {
  if (res.indexOf(v) === -1 && array.every(function(a) {
      return a.indexOf(v) !== -1;
    })) res.push(v);

  return res;
}, [])
)

上面的数组的结果将为空,根据上述条件(至少2个匹配项),我希望它是:

["001", "002", " 001"]

您的回答将不胜感激!

谢谢

1 个答案:

答案 0 :(得分:2)

对于O(N)解决方案(您在.every内部的当前.reduceO(N^2)),可以使用reduce创建一个由字符串索引的对象,其字符串值是该字符串出现的次数。然后,在对象的.filterkeys得到至少两个数的对象:

const input = [["001"," 003"],["002"," 001"],["001"," 002"],["002"," 001"], ["", "001"]];
const obj = input.reduce((a, arr) => {
  arr.forEach((str) => {
    a[str] = (a[str] || 0) + 1;
  });
  return a;
}, {});
const output = Object.keys(obj)
  .filter(key => obj[key] >= 2)
console.log(output);

请注意,因为输入中有两个" 001"字符串,所以它们也包含在输出中。

对于ES5版本,我通过Babel运行了以上内容,并得到了:

var input = [["001", " 003"], ["002", " 001"], ["001", " 002"], ["002", " 001"], ["", "001"]];
var obj = input.reduce(function (a, arr) {
  arr.forEach(function (str) {
    a[str] = (a[str] || 0) + 1;
  });
  return a;
}, {});
var output = Object.keys(obj).filter(function (key) {
  return obj[key] >= 2;
});
console.log(output);