How to Remove an Object from an Array by Key in JavaScript


Suppose we have an array of objects and want to remove an object from the array by key.

let arr = [
  { id: 0, dog: "corgi" },
  { id: 1, dog: "shih tzu" },
  { id: 2, dog: "pug" },
];

We can remove an object with a specific key using the built-in filter method.

arr = arr.filter((elem) => elem.id !== 0);

This will remove all objects with an id of 0.

It also creates a copy of the array and does not modify the original array. This is why we need to reassign the output.

If you’d like to modify the array in place, then you might have to resort to good ol' for loops.

for (let i = 0; i < arr.length; i++) {
  if (arr[i].id === 0) {
    arr.splice(i, 1);
    break;
  }
}