Hello Friends đź‘‹,

Welcome to Infinitbility.

When we are using arrays of objects and we have to remove objects from the array then there are no direct methods to remove them.

Today, we will use javascript findIndex() and splice() methods to remove an object from an array using the object key.

Let take the following sample arrays of objects.

let users = [
  { id: 1, name: 'Infinitbility', email: '[email protected]' },
  { id: 2, name: 'notebility', email: '[email protected]' },
  { id: 3, name: 'stackbility', email: '[email protected]' },
];

In the above arrays, we have to remove the 'stackbility' object from the array.

To remove array property we have to first find property index.

To find index in array, javascript provide findIndex() method.

Suppose, we have an id of 'stackbility' now we can easily search in an array using id property.

let index = users.findIndex((item) => item.id === 3);

console.log('index', index); // 2

Here, when I use findIndex() i got 2 now 2 is our 'stackbility' index value and when we pass this index value in the splice() method it will remove the object from the array.

The following code is a complete example of removing an object from an array.

let users = [
  { id: 1, name: 'Infinitbility', email: '[email protected]' },
  { id: 2, name: 'notebility', email: '[email protected]' },
  { id: 3, name: 'stackbility', email: '[email protected]' },
];

let index = users.findIndex((item) => item.id === 3);

console.log('index', index);

if (index >= 0) {
  users.splice(index, 1);
}

console.log('users', users);

Don’t forget to check the index >= 0 condition else when the index got -1 it will remove the last object.

Output

Javascript remove object from array example
Javascript remove object from array example

Thanks for reading…