Languages
[Edit]
EN

JavaScript - remove array element based on object property

0 points
Created by:
Adnaan-Robin
724

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.

References

  1. Array.prototype.filter() - JavaScript | MDN
  2. Array.prototype.splice() - JavaScript | MDN
  3. Array.prototype.indexOf() - JavaScript | MDN

Alternative titles

  1. JavaScript - remove item from array based on object property value
  2. JavaScript - find and remove objects in array based on key value
  3. JavaScript - remove object from array of objects
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join