简体   繁体   中英

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:

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

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. 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.

  • After making it to 1d array , you can get the unduplicated members using Array.prototype.filter function. (To check if the arr2 includes the item or not, you can use Array.prototype.includes function.).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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