如何使用数组过滤数组数组?

时间:2019-02-14 15:58:09

标签: javascript arrays node.js filter

如何针对数组(myNumbers)对数组(result)进行过滤,以仅获取result中每个数组在myNumbers中出现的值?

具体地,给出:

var result = [02, 03, 04, 06, 07, 11, 12, 13];

var myNumbers = [
    [01, 03, 04, 05, 09, 10, 12, 14],
    [01, 03, 04, 05, 06, 08, 10, 12],
    [01, 02, 04, 05, 06, 08, 10, 12],
    [01, 03, 04, 05, 06, 09, 12, 13],
    [01, 02, 03, 05, 06, 08, 10, 11]
];

输出应为:

[
    [03, 04, 12],
    [03, 04, 06, 12],
    [02, 04, 06, 12],
    [03, 04, 06, 12, 13],
    [02, 03, 06, 11],
]

我一次只能过滤一个数组:

// This only filters it for myNumbers[0]
var confereResult = result.filter(function (number) {
    if (myNumbers[0].indexOf(number) == -1)
            return number;
    console.log(number);
});

我该如何浏览整个列表?

3 个答案:

答案 0 :(得分:5)

您可以映射过滤结果。

var filter = [02, 03, 04, 06, 07, 11, 12, 13],
    array = [[01, 03, 04, 05, 09, 10, 12, 14], [01, 03, 04, 05, 06, 08, 10, 12], [01, 02, 04, 05, 06, 08, 10, 12], [01, 03, 04, 05, 06, 09, 12, 13], [01, 02, 03, 05, 06, 08, 10, 11]],
    result = array.map(a => filter.filter(f => a.includes(f)));

console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:4)

遍历myNumbers数组,并对每行应用一个过滤器。

var result = [02, 03, 04, 06, 07, 11, 12, 13];

var myNumbers = [
    [01, 03, 04, 05, 09, 10, 12, 14],
    [01, 03, 04, 05, 06, 08, 10, 12],
    [01, 02, 04, 05, 06, 08, 10, 12],
    [01, 03, 04, 05, 06, 09, 12, 13],
    [01, 02, 03, 05, 06, 08, 10, 11]
];
myNumbers.forEach((arr, i) => {
  myNumbers[i] = arr.filter((val) => {
    return result.indexOf(val) != -1;
  });
});
console.log(myNumbers);

答案 2 :(得分:0)

您可以循环访问myNumbers并将结果推入数组,例如

var result = [02, 03, 04, 06, 07, 11, 12, 13];

var myNumbers = [
    [01, 03, 04, 05, 09, 10, 12, 14],
    [01, 03, 04, 05, 06, 08, 10, 12],
    [01, 02, 04, 05, 06, 08, 10, 12],
    [01, 03, 04, 05, 06, 09, 12, 13],
    [01, 02, 03, 05, 06, 08, 10, 11]
];
var confereResult = []
myNumbers.forEach(function (val) {
  confereResult.push(result.filter(function (number) {
      if (val.indexOf(number) == -1)
              return number;
  }));
})

console.log(confereResult)