如何从父数组中过滤出子数组?

How to filter out a Sub Array from a Parent Array?

我得到了一个数组 a = [1,2,3,4,5] 和一个包含 a 的一些元素的数组 b = [1,3]。所以它是一种 a.

的子数组

在下面这个for循环中,我可以使用b到"do smething"的元素。现在,我如何在同一个循环中与 a 中不属于 b 的元素进行交互?这意味着 2, 4 and 5 来自 a?如何过滤掉它们?

function action (){
for (var i=0; i<b.length; i++) {

      b[i].x = "do something";


  } 

非常感谢

可以使用filter()函数结合includes()函数来过滤列表:

const diff = a.filter(i => !b.includes(i));

diff 将只包含 a 中不在 b.

中的元素

这称为数组之间的差异。还有很多库将包含某种 diff 数组函数。

您可以在 a 数组上使用 filter 来获取未包含元素的新列表:

a.filter(item => !b.includes(item)).forEach(function(item) {
    console.log(item);
});

您正在寻找这个:a.filter((element) => !b.includes(element))

样本

const a = [1,2,3,4,5];
const b = [1,3]

const elements_in_a_not_in_b = a.filter((element) => !b.includes(element))

console.log(
  elements_in_a_not_in_b
)