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.
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
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
var object = {
10
items: [
11
{ id: 1, name: 'a' },
12
{ id: 2, name: 'b' },
13
{ id: 3, name: 'c' },
14
],
15
};
16
17
var idToRemove = 2;
18
19
_.remove(object.items, {
20
id: idToRemove,
21
});
22
23
console.log(JSON.stringify(object, null, 4));
24
25
</script>
26
</body>
27
</html>
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
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
var object = {
10
items: [
11
{ id: 1, name: 'a' },
12
{ id: 2, name: 'b' },
13
{ id: 3, name: 'c' },
14
],
15
};
16
17
var idToRemove = 2;
18
19
_.remove(object.items, function(currentItem) {
20
return currentItem.id === idToRemove;
21
});
22
23
console.log(JSON.stringify(object, null, 4));
24
25
</script>
26
</body>
27
</html>
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
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
var object = {
10
items: [
11
{ id: 1, name: 'a' },
12
{ id: 2, name: 'b' },
13
{ id: 3, name: 'c' },
14
],
15
};
16
17
var idToDelete = 2;
18
19
object.items = _.filter(object.items, function(currentItem) {
20
return currentItem.id !== idToDelete;
21
});
22
23
console.log(JSON.stringify(object, null, 4));
24
25
</script>
26
</body>
27
</html>