How to Delete an Object from an Array by Name in JavaScript?

Estimated read time 1 min read

In JavaScript, you can delete an object from an array by its name using the splice() method. The splice() method allows you to modify an array by adding or removing elements.

To remove an object from an array by its name, you can use the findIndex() method to find the index of the object in the array and then use the splice() method to remove it.

Here’s an example code snippet:

let myArray = [
  { name: "Object 1", value: 10 },
  { name: "Object 2", value: 20 },
  { name: "Object 3", value: 30 },
  { name: "Object 4", value: 40 }
];

let index = myArray.findIndex(obj => obj.name === "Object 2");

if (index !== -1) {
  myArray.splice(index, 1);
}

console.log(myArray);

In the above code, the findIndex() method is used to find the index of the object with the name “Object 2”. If the object is found, the splice() method is used to remove the object from the array.

Note that the splice() method modifies the original array, so make sure to use it carefully.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply