Search code examples
lodash

remove objects with a specific `key: value` from an array


I have an array of object and need to use lodash to remove some of those objects with a specific key: value, for instance:

[
{id:1,b:22},
{id:2,b:44},
{id:3,b:56},
{id:4,b:-29}
]

I need to remove all object with id of 1 and 3.

i know the way below but was wondering if there is a shorter way:

    var array = [
    {id:1,b:22},
    {id:2,b:44},
    {id:3,b:56},
    {id:4,b:-29}
    ];

 _.remove(array, function(n) {
  return _.includes([ 1,3 ], n.id);
});

Solution

  • You could use pullAllBy and provide the elements to be removed as the 2nd parameter.

    let data = [{id:1,b:22},{id:2,b:44},{id:3,b:56},{id:4,b:-29}]
    
    const result = _.pullAllBy(data, [{id:1},{id:3}], 'id')
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

    Note that this method mutates the array. If you do not want that use _.differenceBy

    Using ES6 and arrow functions + filter to get the values and not mutate the array will also get you somewhat of a short version:

    let data = [{ id: 1, b: 22 }, { id: 2, b: 44 }, { id: 3, b: 56 }, { id: 4, b: -29 }]
    
    const result = data.filter(x => ![1,3].includes(x.id))
    console.log(result)