【问题标题】:Remove duplicates from multidimensional arrays (JS)从多维数组(JS)中删除重复项
【发布时间】:2021-02-16 17:29:45
【问题描述】:

我有两个带时间的数组,我想删除重复的数组,数组可能如下所示:

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))
    }
  }
}

【问题讨论】:

  • I have tried ... I also tried ... 显示您尝试过的内容,您显示的代码甚至没有尝试解决问题
  • 请清理您的数组声明以匹配您的代码并显示预期的输出。您可以通过单个 filter() 调用来完成此操作,并且无需 for 循环。

标签: javascript arrays filter splice


【解决方案1】:
  • 输入数组(arr1arr2)是多维数组,所以需要使用Array.prototype.flat()函数将它们变成一维数组。

  • 到达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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-26
    • 2014-05-26
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2017-07-23
    相关资源
    最近更新 更多