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


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 => obj.id !== 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 => obj.id !== id); // arr stays the same
// vs.
arr = arr.filter(obj => obj.id !== id); // arr updates as expected