简体   繁体   English

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

[英]Remove duplicates from multidimensional arrays (JS)

I have two arrays with times and I want to remove the duplicates, the arrays could look like this:我有两个带时间的数组,我想删除重复项,数组可能如下所示:

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

so I've tried to first loop through the second array with 2 for loops like this:所以我尝试首先用 2 个 for 循环遍历第二个数组,如下所示:

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

which gives me the values: 11:00, 13:00这给了我值:11:00, 13:00

now I have tried to go with a while loop a splice the array if the values match, but this didn't work very well.现在,如果值匹配,我尝试使用 while 循环拼接数组,但这效果不佳。 I also tried the filter method, but with no success我也尝试了过滤方法,但没有成功

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))
    }
  }
}
  • The input array ( arr1 , arr2 ) are multi-dimensional arrays so it is needed to make them to 1d array using Array.prototype.flat() function.输入数组( arr1arr2 )是多维数组,因此需要使用Array.prototype.flat()函数将它们变成一维数组。

  • After making it to 1d array , you can get the unduplicated members using Array.prototype.filter function.使其成为1d array ,您可以使用Array.prototype.filter函数获取不重复的成员。 (To check if the arr2 includes the item or not, you can use Array.prototype.includes function.). (要检查 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM