EN
JavaScript - remove element from array using lodash
0
points
In this article, we would like to show you how to remove element from array using lodash in JavaScript.
1. Using _.remove()
In this example, we present a simple use case of _.remove()
method to delete the element with given idToRemove
from array of items
inside the object
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
<script>
var object = {
items: [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
],
};
var idToRemove = 2;
_.remove(object.items, {
id: idToRemove,
});
console.log(JSON.stringify(object, null, 4));
</script>
</body>
</html>
2. Using _.remove()
with predicate function
In this example, we use _.remove()
method with a predicate function to delete the element with given idToRemove
from array of items
inside the object
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
<script>
var object = {
items: [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
],
};
var idToRemove = 2;
_.remove(object.items, function(currentItem) {
return currentItem.id === idToRemove;
});
console.log(JSON.stringify(object, null, 4));
</script>
</body>
</html>
3. Using _.filter()
In this example, we use _.filter()
method to create a new filtered array of items
inside the object
and assign it to the same object
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
<script>
var object = {
items: [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
],
};
var idToDelete = 2;
object.items = _.filter(object.items, function(currentItem) {
return currentItem.id !== idToDelete;
});
console.log(JSON.stringify(object, null, 4));
</script>
</body>
</html>