Fred J. Fred J. - 1 month ago 5
Javascript Question

Remove all certain objects from an array

Given the array:

myArr = [
{'a':1},
{'b':1},
{'b':2},
{'a':1},
{'b':2}
]


And the index
0
, which has the object
{'a':1}
, I would like to get back the array:
[{'b':1},{'b':2},{'b':2}]
keeping the original sort order.

That is removing the object in index
0
and all other objects which are the equivalent.
Is there an elegant way?

Answer

If you want to remove the same object, it is simple:

    a1 = { a: 1 }
    b1 = { b: 1 }
    b2 = { b: 2 }
    myArr = [ a1, b1, b2, a1, b2 ]
    
    var filtered = myArr.filter(o => o != a1)
    console.log(filtered);
    // [ {b: 1}, {b: 2}, {b: 2} ]

However, if you want to remove an equivalent object, it gets complicated, because by default JavaScript does not have an object equivalence test. You can implement one yourself, or rely on one of the libraries like lodash:

var myArr = [
  {'a':1},
  {'b':1},
  {'b':2},
  {'a':1},
  {'b':2}
];

var filtered = _.filter(myArr, o => !_.isEqual(o, {a: 1}));
console.log(filtered);
// [ {b: 1}, {b: 2}, {b: 2} ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>

Then again, if you're using lodash, you might as well just use it to the full extent:

var myArr = [
  {'a':1},
  {'b':1},
  {'b':2},
  {'a':1},
  {'b':2}
];

var filtered = _.differenceWith(myArr, [{a: 1}], _.isEqual);
console.log(filtered);
// [ {b: 1}, {b: 2}, {b: 2} ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>

which basically does the same thing, but a bit more readably.