how to remove object from array with lodash

1

Personally I 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 it 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;
})
    
asked by anonymous 23.05.2018 / 18:28

1 answer

1

First, you're comparing objects with == , which does not work the way you think.

See this small example:

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

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

It does not even have to do with a strong or weak comparison, but with the fact that it is between objects. Comparison between objects only gives true if both references point to the same object. In your case, since you are already using lodash, you can use loadash's isEqual to solve this problem, which will return 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>

Withthisyoucaneasilyfixthe_.removetotherequiredlogic:

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>

Youcanevensimplify/compactabitinremoveusinga Arrow Function :

_.remove(selectedSeats, s => _.isEqual(s, seat));
    
23.05.2018 / 19:45