0

I have two multidimensional arrays and need to remove all the arrays from array A that exist in array B. I've tried it this way with no luck:

var arrayA = [[0,1], [2,0], [0,3], [4,0], [0,5]];

var arrayB = [[0,1], [0,3]];

arrayA = arrayA.filter( function( el ) {
  return arrayB.indexOf( el ) < 0;
} );

alert(arrayA);

This works when the elements in arrayA and arrayB are single values and but when they are arrays. Not sure what I am doing wrong?

user3688241
  • 3,015
  • 2
  • 14
  • 13

3 Answers3

3

Assuming the inner arrays are always in the same order to match:

for (var i = 0; i < arrayA.length; i++) {
    for (var j = 0; j < arrayB.length; j++) {
        if (JSON.stringify(arrayA[i]) == JSON.stringify(arrayB[j])) {
            arrayA.splice(i, 1);
            break;
        }
    }
}

Fiddle: http://jsfiddle.net/o2qk7hjd/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

You can do it like this

var arr = arrayA.map(function(x){ return x + "" }); // convert the array to string
arrayB.forEach(function(e) {
    var idx = (arr.indexOf(e + "")); // find the index
    arr.splice(idx, 1); // remove it
});
arrayA = arr.map(function(x) { return x.split(","); });
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

Array.prototype.indexOf uses strict equals comparison to check if elements are equal. This wont work for reference types since [] === []; is false. You can either use @tymeJV solution which is O(lenA*lenB) complexity or preindex arrayB making it O(lenA + lenB)

Demo.

function index(arr) {
    return arr.reduce(function(acc, item){
        return acc[JSON.stringify(item)] = item, acc
    }, {});    
}
var arrayA = [[0,1], [2,0], [0,3], [4,0], [0,5]];

var arrayB = [[0,1], [0,3]];

var indexB = index(arrayB);

arrayA = arrayA.filter( function( el ) {
  return !(JSON.stringify(el) in indexB);
} );

console.log(arrayA);

UPD If the order of elements inside inner arrays is not quaranteed you can use sort. This will make this task O(lenA*log(lenA) + lenB*log(lenB))

Demo 2.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98