W3jar
292 words
1 minutes

How to Remove Object from an Array by Property in JavaScript

To remove an object from an array based on a specific property in JavaScript, you can use several methods. Here’s a step-by-step approach for a common scenario where you want to remove an object that matches a particular property value.

Example Scenario#

Assume you have an array of objects, and you want to remove an object with a specific id value.

const array = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" },
];

Methods to Remove an Object by Property#

1. Using filter Method#

The filter method creates a new array with all elements that pass the test implemented by the provided function. You can use it to exclude the object you want to remove.

const idToRemove = 2;

const updatedArray = array.filter((item) => item.id !== idToRemove);

console.log(updatedArray);

Explanation:

  • array.filter(item => item.id !== idToRemove): Creates a new array that includes all items except the one where item.id equals idToRemove.

2. Using splice Method#

If you want to modify the original array, you can use splice to remove the object directly. First, you need to find the index of the object to remove.

const idToRemove = 2;

// Find the index of the object to remove
const index = array.findIndex((item) => item.id === idToRemove);

if (index !== -1) {
    // Remove the object from the array
    array.splice(index, 1);
}

console.log(array);

Explanation:

  • array.findIndex(item => item.id === idToRemove): Finds the index of the object where item.id equals idToRemove.
  • array.splice(index, 1): Removes the object at the found index. The 1 indicates that only one element should be removed.

Summary#

  • filter Method: Best for creating a new array with the object removed, leaving the original array unchanged.
  • splice Method: Best for modifying the original array in place.

Choose the method based on whether you want to keep the original array unchanged or modify it directly.