How do you remove an object from a JavaScript array by matching a property value? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you remove an object from a JavaScript array by matching a property value?

message-square
0

To remove objects from a JavaScript array by matching a property value without mutating the original array, use arr.filter((item) => ...) after validating that items is a non-null array and propName is a safe, non-empty string key. To remove only the first matching object non-mutatingly, find its index with arr.findIndex(...) and use arr.toSpliced(index, 1) (or .filter() with a found flag); if you intentionally need in-place mutation on a local array, locate the index and call arr.splice(index, 1) after bounds checks.


1. Non-Mutating Removal by Matching Property Value (.filter())

Guard against non-array inputs, null/primitive items, and unsafe keys (__proto__, constructor, prototype), and return a new array excluding objects whose property matches the target value (Object.is for strict/safe equality including NaN):

// Remove objects from an array where item[propName] matches targetValue without mutating input
function removeObjectsByProperty(items, propName, targetValue, { removeAll = true } = {}) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an Array.");
  }

  if (typeof propName !== "string" || propName.trim() === "") {
    throw new TypeError("Expected propName to be a non-empty string.");
  }

  const key = propName.trim();
  if (key === "__proto__" || key === "constructor" || key === "prototype") {
    throw new RangeError(`Refusing unsafe property key "${key}".`);
  }

  let removedCount = 0;
  const filtered = items.filter((item) => {
    const isRecord = typeof item === "object" && item !== null;
    const hasOwn = isRecord && Object.prototype.hasOwnProperty.call(item, key);
    const matches = hasOwn && Object.is(item[key], targetValue);

    if (matches && (removeAll || removedCount === 0)) {
      removedCount += 1;
      return false;
    }

    return true;
  });

  return Object.freeze({
    items: filtered,
    removedCount
  });
}

// Example usage:
const users = Object.freeze([
  { id: 1, name: "Amina" },
  { id: 2, name: "Bilal" },
  { id: 3, name: "Bilal" }
]);

const withoutFirstBilal = removeObjectsByProperty(users, "name", "Bilal", { removeAll: false });
console.log(withoutFirstBilal.items); // [{ id: 1, name: "Amina" }, { id: 3, name: "Bilal" }]
console.log(users); // Original array remains frozen and untouched
  • Non-mutating & Object.freeze() safe: Returns a new filtered array without modifying users or any element object.
  • Own-property & Object.is() check: Avoids matching inherited Object.prototype keys and handles NaN cleanly.

2. Removing Only the First Match in Place (findIndex + splice) When Mutation Is Intended

When mutating a local, non-frozen array in place is intentional and you only want to drop the first matching object, locate its index with findIndex() and splice a single element after verifying the index is non-negative:

// Remove the first matching object in place on a mutable array
function removeFirstObjectByPropertyInPlace(targetArray, propName, targetValue) {
  if (!Array.isArray(targetArray)) {
    throw new TypeError("Expected targetArray to be an Array.");
  }

  if (Object.isFrozen(targetArray)) {
    throw new TypeError("Cannot mutate a frozen array.");
  }

  if (typeof propName !== "string" || propName.trim() === "") {
    throw new TypeError("Expected propName to be a non-empty string.");
  }

  const key = propName.trim();
  const matchIndex = targetArray.findIndex(
    (item) =>
      typeof item === "object" &&
      item !== null &&
      Object.prototype.hasOwnProperty.call(item, key) &&
      Object.is(item[key], targetValue)
  );

  if (matchIndex < 0) {
    return null;
  }

  const [removedItem] = targetArray.splice(matchIndex, 1);
  return removedItem ?? null;
}

// Example usage:
const tasks = [
  { id: "t-101", done: false },
  { id: "t-102", done: true }
];
const removed = removeFirstObjectByPropertyInPlace(tasks, "id", "t-101");
console.log("Removed:", removed); // { id: "t-101", done: false }
console.log("Remaining:", tasks); // [{ id: "t-102", done: true }]
  • Guards matchIndex < 0: Prevents arr.splice(-1, 1) from accidentally deleting the last element of the array when no match is found.
  • Returns removed item (or null): Gives clear visibility into whether a match existed.

3. Common Traps to Avoid

Removing objects from an array by property value often runs into a few pitfalls:

  • Passing findIndex() result (-1) directly to arr.splice(idx, 1): When no object matches, findIndex returns -1; arr.splice(-1, 1) deletes the last element in the array unless you check if (idx !== -1) first.
  • Not guarding null or undefined elements inside the array: Accessing item.id when an array contains null or undefined throws TypeError: Cannot read properties of null.
  • Removing all duplicates when only one match should be removed: .filter((x) => x.id !== targetId) removes every matching item—use { removeAll: false } or findIndex + splice when only a single record should be deleted.

TL;DR: Use arr.filter((item) => item && !Object.is(item[key], value)) for non-mutating removal of matching objects, or guard const idx = arr.findIndex(...) (idx !== -1) before calling arr.splice(idx, 1) when intentional in-place removal of a single match is needed.