从多维数组(JS)中删除重复项

时间:2020-11-04 01:08:35

标签: javascript arrays filter splice

我有两个带时间的数组,我想删除重复项,这些数组可能看起来像这样:

arr1 = [ ['11:00','12:00','13:00'] ]
arr2 = ['11:00'],['13:00']

因此,我尝试使用2个for循环首先遍历第二个数组:

for (i = 0; i < timeslotsBusy.length; i++) {
  for (j = 0; j < timeslotsBusy[i].length; j++) {
    console.log(timeslotsBusy[i][j]);
  }
}

为我提供的值是:11:00、13:00

现在,我尝试过使用while循环,如果值匹配,则对数组进行拼接,但是效果不是很好。我也尝试过过滤器方法,但没有成功

for (i = 0; i < timeslotsBusy.length; i++) {
  for (j = 0; j < timeslotsBusy[i].length; j++) {
    for (x = 0; x < timeslotsFree.length; x++) {
      timeslotsFree = timeslotsFree[x]
      timeslotsFree = timeslotsFree.filter(val => timeslotsBusy[i][j].includes(val))
    }
  }
}

1 个答案:

答案 0 :(得分:1)

  • 输入数组(arr1arr2)是多维数组,因此需要使用Array.prototype.flat()函数将它们设为1d数组。

  • 进入1d array后,您可以使用Array.prototype.filter函数获得未重复的成员。 (要检查arr2是否包含该项目,可以使用Array.prototype.includes函数。)。

const arr1 = [ ['11:00','12:00','13:00'] ];
const arr2 = [ ['11:00'],['13:00'] ];

const arr1Flat = arr1.flat();
const arr2Flat = arr2.flat();

const output = arr1Flat.filter((item) => !arr2Flat.includes(item));
console.log(output);

相关问题