1

So here's the proposed problem.

Compare two arrays and return a new array with any items not found in both of the original arrays.

Here's what I have so far.

function diff(arr1, arr2) {
    for (var a in arr1) {
        for (var b in arr2) {
            if (arr1[a] == arr2[b]){
                arr2.splice(b,1);
            }
        }
    }
    return arr2;
}

diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);

This code basically just compares each value of the first array with the second one. If a match is found it then removes the item using the splice function.

This works great for arrays that are one dimensional but how can I get it to work for multidimensional arrays such as:

diff([1, 2, 3, 5], [1, [2, 3], [4, 5]]);

What if these arrays are not just two dimensions but any number of dimensions. I should be able to iterate through every element of every array no matter they are set up.

gevorg
  • 4,835
  • 4
  • 35
  • 52
Mike s
  • 53
  • 4
  • [Merge/flatten an Array of Arrays in JavaScript?](http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript) – Andreas Jul 23 '15 at 16:04
  • And don't use `for ... in ...` to iterate over an array. – Andreas Jul 23 '15 at 16:09
  • Thank you! That led me to a solution, a very messy one at the moment but I've managed to accomplish what I was going for. Why shouldn't I use for..in... Isn't that what is was designed for? – Mike s Jul 23 '15 at 16:33
  • [`for (variable in object)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in): "The for..in statement iterates over the **enumerable properties of an object**, in arbitrary order. For each distinct property, statements can be executed."; For arrays you should be using [`for ([initialization]; [condition]; [final-expression])`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) instead – Andreas Jul 24 '15 at 04:36

1 Answers1

0

With lodash you can do this :

var a = [1, 2, 3, 5, 7], b = [1, [2, 3], [4, 5, [7]]];

var result = _.filter(_.flattenDeep(b), function(item){
  return a.indexOf(item) === -1;
});

console.log(result);
$("body").append(JSON.stringify(result))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<body></body>
Thom-x
  • 841
  • 1
  • 6
  • 20