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.
Practical example
In this example, we use filter() method to remove all elements from users array which name property is equal to the specific value.
// ONLINE-RUNNER:browser;
var users = [
{ name: 'Kate', age: 23 },
{ name: 'Tom', age: 24 },
{ name: 'Ann', age: 25 },
];
users = users.filter(function(user) {
return user.name !== 'Ann';
});
console.log(JSON.stringify(users, null, 4));
Note:
The
filter()method doesn't modify the original array.
Using findIndex() and splice() methods
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.
// ONLINE-RUNNER:browser;
var users = [
{ name: 'Kate', age: 23 },
{ name: 'Tom', age: 24 },
{ name: 'Ann', age: 25 },
];
var nameToRemove = 'Tom';
var index = users.findIndex(object => object.name === nameToRemove);
users.splice(index, 1);
console.log(JSON.stringify(users, null, 4));
Note:
The
splice()method modifies the original array.