How To Remove An Object from An array based on Object Property in JavaScript – Definitive Guide

Each JavaScript object has its own properties and functions.

You can remove an object from an array based on object property using the index and the splice() method.

This tutorial teaches you the different methods to remove an element from an array based on object property.

Remove An Object from An array based on Object Property Using Splice()

The splice() method removes an object from a specific index of an array.

To delete an object based on its property,

Use this method when you want to delete the element from the same array object instead of creating a new array object.

Code

The following code explains how to remove an object with id – 2.

const arr = [{ id: 0, name: "Bob" },
  { id: 1, name: "Ram" },
  { id: 2, name: "Peter" }];

const indexOfObject = arr.findIndex(object => {
  return object.id === 2;
});

arr.splice(indexOfObject);

console.log(arr);

Output

[{
  id: 0,
  name: "Bob"
}, {
  id: 1,
  name: "Ram"
}]

In other words, this is also known as finding and removing objects in an array based on a key value in JavaScript.

Remove An Object from An array based on Object Property Using Filter()

The filter() method creates a new array from an existing array based on the values that pass a specific condition.

To remove an object from an array based on object property,

  • filter the array to exclude the item with a specific property value

Use this method when you want to create a new array excluding the element that matches a specific condition.

Code

The following code demonstrates how to exclude the object with id 2 and create an array with other objects.

const arr = [{ id: 0, name: "Bob" },
  { id: 1, name: "Ram" },
  { id: 2, name: "Peter" }];

const filteredArray = arr.filter(object => {
  return object.id !== 2;
});

console.log(filteredArray)

Output

[{
  id: 0,
  name: "Bob"
}, {
  id: 1,
  name: "Ram"
}]

Remove An Object from An array based on Object Property Using Del Keyword

The delete keyword will remove an object from an array but will not modify the array length. The value in the removed index will be replaced with the undefined keyword.

To remove an array element based on its property,

  • Find the element’s index using findindex()
  • pass it to the delete keyword

Use this method when you want to delete an element from an array based on its property, but *do not want to change the array length.

Code

const arr = [{ id: 0, name: "Bob" },
  { id: 1, name: "Ram" },
  { id: 2, name: "Peter" }];

const indexOfObject = arr.findIndex(object => {
  return object.id === 2;
});

delete arr[indexOfObject];

console.log(arr);

Output

[{
  id: 0,
  name: "Bob"
}, {
  id: 1,
  name: "Ram"
}, undefined]

Additional Resources

Leave a Comment