How to remove Object from Array using JavaScript ?

To remove an object from an array in JavaScript, you can use various methods depending on whether you need to modify the original array or create a new one, and whether you want to remove the first occurrence, all occurrences, or a specific instance. Below are detailed approaches with examples:

1. Using splice() and findIndex()

Use Case: Remove the first occurrence by a specific property (e.g., id).
Mutates Original Array: Yes.

const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
];

// Find the index of the object with id = 2
const index = users.findIndex(user => user.id === 2);

if (index !== -1) {
  users.splice(index, 1); // Remove 1 element at the found index
}

console.log(users);
// Output: [{ id: 1, name: 'John' }, { id: 3, name: 'Bob' }]

2. Using filter()

Use Case: Create a new array excluding the object(s) matching a condition.
Mutates Original Array: No.

const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
];

// Create a new array without the object with id = 2
const filteredUsers = users.filter(user => user.id !== 2);

console.log(filteredUsers);
// Output: [{ id: 1, name: 'John' }, { id: 3, name: 'Bob' }]

3. Remove by Object Reference

Use Case: Remove the exact object (reference-based).
Mutates Original Array: Yes.

const jane = { id: 2, name: 'Jane' };
const users = [
  { id: 1, name: 'John' },
  jane, // Reference to the same object
  { id: 3, name: 'Bob' }
];

// Find the index using the reference
const index = users.indexOf(jane);

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

console.log(users);
// Output: [{ id: 1, name: 'John' }, { id: 3, name: 'Bob' }]

4. Remove All Occurrences

Use Case: Remove all objects matching a condition (e.g., multiple duplicates).
Mutates Original Array: Depends on method.

Using filter():

const users = [
  { id: 2, name: 'Jane' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
];

// Remove all objects with id = 2
const filteredUsers = users.filter(user => user.id !== 2);
console.log(filteredUsers); // Output: [{ id: 3, name: 'Bob' }]

Using a for Loop (Mutates Original Array):

let users = [
  { id: 2, name: 'Jane' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
];

for (let i = users.length - 1; i >= 0; i--) {
  if (users[i].id === 2) {
    users.splice(i, 1);
  }
}

console.log(users); // Output: [{ id: 3, name: 'Bob' }]

5. Using pop() or shift()

Use Case: Remove the last or first element (not specific to objects).
Mutates Original Array: Yes.

// Remove the last object
users.pop();

// Remove the first object
users.shift();

Avoid delete Operator

The delete operator removes the property of an object but leaves the array index empty (sets it to undefined), which is generally not desired:

delete users[1]; // Results in [ { id:1 }, <empty slot>, { id:3 } ]

Summary Table

MethodMutates Original ArrayUse Case
splice() + findIndexYesRemove first occurrence by condition.
filter()NoCreate new array without matching objects.
indexOf() + spliceYesRemove exact object by reference.
for loop + spliceYesRemove all occurrences (manual iteration).

Edge Cases

  1. Object Not Found:
    findIndex() returns -1, so check before using splice().
  2. Empty Array:
    Handle gracefully to avoid errors.
  3. No Unique Identifier:
    Use a combination of properties to identify the object (e.g., user.name === 'Jane' && user.age === 30).

By understanding these methods, you can choose the best approach for your specific use case.

Leave a Reply

Your email address will not be published. Required fields are marked *