2

我在下面的代码中有两个数组——一个matches是主数组,另一个played是用来过滤主数组中的元素:

var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]];
var played = [2,5];

我需要根据已播放的数组过滤掉匹配项中的元素,这意味着如果有 2 或 5 个,则将其完全删除。播放的数组也可以是任意长度,最小值为 1。

预期输出应该是

[[1,4],[3,1],[3,4]];

所以我尝试了这段代码,但它没有产生我想要的结果。

var result = matches.map(x => x.filter(e => played.indexOf(e) < 0))

那么无论如何要实现这一目标?

4

3 回答 3

1

您可以检查some并排除不需要的数组。

var matches = [[1, 4], [3, 1], [5, 2], [3, 4], [4, 5], [2, 1]],
    played = [2, 5],
    result = matches.filter(a => !a.some(v => played.includes(v)));

console.log(result);

于 2020-03-30T20:35:36.670 回答
1

过滤时,检查其中.every一个子数组元素是否不包含在[2, 5]

var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]];
var played = [2,5];

const result = matches.filter(
  subarr => played.every(
    num => !subarr.includes(num)
  )
);
console.log(result);

于 2020-03-30T20:33:50.750 回答
0

另一种方法是创建一个 Set ofplayed以避免一次又一次地迭代它:

var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]];
var played = new Set([2,5]);
var out = matches.filter(a => !a.some(num => played.has(num)));
console.info(out)

于 2020-03-30T20:42:12.413 回答