0

Is it possible to drop an exact matching array out from another array?

Two arrays:

let array1: any[] = [[1], [2,3], [1,2]];
let array2: any[] = [[1]];

What I want to do:

function deleteArrayFromArray(array2) {
  // delete given array2 from array1
}

Result should be:

array1 or new array --> [[2,3], [1,2]]

Is there something like lodash's filter, but with an exact array to array comparison:

_.filter(array1, array2);
Mikel Wohlschlegel
  • 1,364
  • 1
  • 11
  • 23
  • 2
    If the order is important... just use `JSON.stringify()` – kemicofa ghost Feb 25 '19 at 15:59
  • I know they marked it as duplicate but maybe this will help you in your specific case. `function deleteArrayFromArray(array1, array2) { return array1.map(JSON.stringify).filter((x) => !array2.map(JSON.stringify).includes(x)).map(JSON.parse) }` `deleteArrayFromArray( [[1], [2,3], [1,2]], [[1]])` a functional approach using es6. – Jordan Maduro Feb 25 '19 at 16:24

1 Answers1

1

You can filter one array and compare object with JSON.stringify with second array and then use slice method to delete from one array,

let array1 = [[1], [2,3], [1,2]]

let array2 = [[1]];
//console.log(array1);    
array1.filter(function(obj) {
 // JSON.stringify(obj)==JSON.stringify(obj)
  for( var i=0, len=array2.length; i<len; i++ ){
          if(JSON.stringify(obj)==JSON.stringify(array2[i]) ) {
              array1.splice(i, 1);
             return false;
          }
      }
 return true; 
});
console.log(array1);
Vikas
  • 6,868
  • 4
  • 27
  • 41