How to Find and Delete an Object in an Array in JavaScript?

Estimated read time 2 min read

You can use the Array.prototype.splice() method to find and delete an object in an array in JavaScript.

Here’s an example that demonstrates how to find and delete an object in an array based on a specific property:

const people = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Jim", age: 35 },
  { name: "Jack", age: 40 },
  { name: "Jill", age: 20 }
];

const personToDelete = { name: "Jim", age: 35 };

const index = people.findIndex(person => person.name === personToDelete.name && person.age === personToDelete.age);

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

console.log(people);
/*
Output:
[
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Jack", age: 40 },
  { name: "Jill", age: 20 }
]
*/

In this example, the findIndex() method is used to find the index of the object in the people array that matches the personToDelete object. If the index is found, the splice() method is used to delete the object from the people array. The splice() method takes two arguments: the first argument is the index of the object to be deleted, and the second argument is the number of objects to be deleted. In this case, we’re deleting only one object, so the second argument is 1.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply