0

How to find differences between two arrays which have arrays nested inside? I tried different approaches including filter but not succeeded. We have two arrays:

var arr1 = [ [1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6]];
var arr2 = [ [1, 1], [1, 2], [1, 5]];

All I need is to get an array with elements which do not exist in the first array as a result: [[1, 3], [1, 4], [1, 6]]

me-and-viy
  • 51
  • 8
  • Show your best attempt. Did you read any of the questions about how to compare arrrays? – Barmar Oct 30 '19 at 22:35
  • Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – maciejze Oct 30 '19 at 22:36
  • If `arr2` had elements that did not exist in `arr1` would you want those as well? That is, are you looking for an element-wise `arr1 & !arr2`, or `arr1 ^ arr2`? – Patrick Roberts Oct 30 '19 at 22:44

1 Answers1

2

You can filter on arr1 with the predicate there isn't some element in arr2 where all items match.

var arr1 = [ [1, 1], [1, 2, 3], [1, 3], [1, 4], [1, 5], [1, 6]];
var arr2 = [ [1, 1], [1, 2], [1, 5]];

let filtered = arr1.filter(a => 
   !arr2.some(a2 => a.length === a2.length && a2.every((n, i) => n === a[i] ))
)

console.log(filtered)

You can make this more efficient at the expense of additional space if your lists are long enough to warrant it.

Mark
  • 90,562
  • 7
  • 108
  • 148
  • 1
    The complexity is O(n^3) with the nested looping. Probably better to create a Map ? – Dhananjai Pai Oct 30 '19 at 22:52
  • @DhananjaiPai it really depends on the data. Creating and populating a map will be slower up until the point it's not and you will still need some way to test equality be comparing arrays or stringified versions of them. – Mark Oct 30 '19 at 22:54