How to Delete Element in Array Based on Object Key in JavaScript

Published Feb 13, 2022  ∙  Updated May 2, 2022

How can we delete an object in an array based on its key in JavaScript?

We can easily achieve this using filter().

Suppose we have an array arr that contains an id field. We want to delete all objects in arr based on id.

const deleteBasedOnId = (arr, id) => {
  return arr.filter(obj => !== id);

Note that filter() does not perform an in-place operation. This means that arr will not be changed unless we reassign the output.

arr.filter(obj => !== id); // arr stays the same
// vs.
arr = arr.filter(obj => !== id); // arr updates as expected