0

I have two arrays:

var firstArr = [1,2,3,4,5];
var secondArr = [2,3];

How can I get an array like this:

[1,4,5]

I would like to use a solution that could be used when elements of the array are objects with multiple properties.

amp
  • 11,754
  • 18
  • 77
  • 133

2 Answers2

2

Use filter:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

For example:

firstArr.filter(function(item){ 
    return secondArr.indexOf(item) === -1; 
});
CD..
  • 72,281
  • 25
  • 154
  • 163
  • 1
    For OP's second request (array elements are objects), it should be noted that this will only work if *the same* object is present in both arrays, and not just a *copy* of that object. – Siguza Jun 28 '15 at 15:27
0

You can use this Function to remove items.

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');
Siguza
  • 21,155
  • 6
  • 52
  • 89