0

I have two arrays:

var array1 = [a,b,c,d];
var array2 = [1,2,a,b];

I need to have a function that returns an array of the items not in the second Array.

var notInSecond = [c,d];

Does anyone know how to do this?

Thanks.

Leonardo Amigoni
  • 2,237
  • 5
  • 25
  • 35

1 Answers1

2
var notInSecond = array1.slice(0); // Creates a clone of array1
for (var i = 0, j; i < array2.length; i++) {
    j = notInSecond.indexOf(array2[i]);
    if (j > -1) notInSecond.splice(j, 1);
}

Keep in mind that indexOf for arrays isn't available for IE8 and lower and it must be emulated. I'm also assuming that array1 doesn't contain duplicates.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
  • Very nice! Works perfectly and simple. Thank you. – Leonardo Amigoni May 21 '12 at 17:56
  • You're welcome. As a bonus, you can use this one-liner too: `var notInSecond = array1.filter(function(a) {return array2.indexOf(a) === -1;});`. I didn't use it because it's slower due to repeated calls to the `filter` callback function passed as the argument. As before, `filter` must be emulated for older browsers. – MaxArt May 21 '12 at 18:15
  • I would not recommend this answer to be an efficient one. You are cloning an array and manually removing values from that array which is expensive. It would be best to create a new empty array and add values as you loop. – Alex V Jan 01 '15 at 23:31