EN
JavaScript - remove array element based on object property
0 points
In this article, we would like to show you how to remove array element based on object property using JavaScript.
In this example, we use filter()
method to remove all elements from users
array which name
property is equal to the specific value.
xxxxxxxxxx
1
var users = [
2
{ name: 'Kate', age: 23 },
3
{ name: 'Tom', age: 24 },
4
{ name: 'Ann', age: 25 },
5
];
6
7
users = users.filter(function(user) {
8
return user.name !== 'Ann';
9
});
10
11
console.log(JSON.stringify(users, null, 4));
Note:
The
filter()
method doesn't modify the original array.
In this example, we use findIndex()
method to find the index
of the user we want to remove (searched by name
property). Then we use splice()
method to remove the user under the index. This solution removes only the first occurrence of a user with given name
.
xxxxxxxxxx
1
var users = [
2
{ name: 'Kate', age: 23 },
3
{ name: 'Tom', age: 24 },
4
{ name: 'Ann', age: 25 },
5
];
6
7
var nameToRemove = 'Tom';
8
9
var index = users.findIndex(object => object.name === nameToRemove);
10
11
users.splice(index, 1);
12
13
console.log(JSON.stringify(users, null, 4));
Note:
The
splice()
method modifies the original array.