how to remove object from the lodash array

Asked

Viewed 256 times

1

People almost do not use lodash and I am not able to remove an element from the array using remove. example:

seat = { x:1, y:2 };
selectedSeats = [{ x:1, y:1 }, { x:1, y:2 }];
_.remove(selectedSeats,function(s){
    return s === seat;
})

I’ve tried that too:

seat = { x:1, y:2 };
selectedSeats = [{ x:1, y:1 }, { x:1, y:2 }];
_.remove(selectedSeats,function(s){
    return s.x === seat.x && s.y === seat.y;
})

1 answer

1


First of all, you’re comparing objects with ==, that doesn’t work the way you’re thinking.

Look at this little example:

seat = { x:1, y:2 };
selectedSeats = [{ x:1, y:1 }, { x:1, y:2 }];

console.log(seat == selectedSeats[1]); //false

It’s not even about strong or weak comparison, it’s about the fact that it’s between objects. Comparison between objects only gives true if both references point to the same object. In your case as you are already using lodash, you can use the isEqual loadash to solve this problem, which will return you true if both objects have the same properties and values.

seat = { x:1, y:2 };
selectedSeats = [{ x:1, y:1 }, { x:1, y:2 }];

console.log(_.isEqual(seat, selectedSeats[1])); //true
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>

With this you can easily fix the _.remove to the necessary logic:

seat = { x:1, y:2 };
selectedSeats = [{ x:1, y:1 }, { x:1, y:2 }];
_.remove(selectedSeats,function(s){
    return _.isEqual(s, seat); //utiliza o isEqual para comparar
})

console.log(selectedSeats);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>

You can even simplify/compress a bit on remove using a Arrow Function:

_.remove(selectedSeats, s => _.isEqual(s, seat));
  • Very good, I ended up solving otherwise, but I had not seen this method of the lodash

Browser other questions tagged

You are not signed in. Login or sign up in order to post.