How Lodash _.remove Modifies Array Length

This article explains how the Lodash _.remove method mutates an array in place and alters its .length property immediately upon execution. You will learn the mechanics behind its in-place mutation, how elements are shifted, and why the native JavaScript .length property updates synchronously when the operation finishes.


In-Place Mutation vs. Non-Mutating Alternatives

Unlike non-mutating methods like Array.prototype.filter or Lodash's _.filter—which return a new array and leave the source intact—_.remove directly alters the target array passed to it. It returns an array of the removed elements while modifying the original array to contain only the elements that failed the predicate check.

const numbers = [1, 2, 3, 4, 5];
const evens = _.remove(numbers, (n) => n % 2 === 0);

console.log(numbers);        // [1, 3, 5]
console.log(numbers.length); // 3
console.log(evens);          // [2, 4]

The Mechanism Behind Updating .length

Lodash's _.remove manages array length alteration through a two-step in-place compacting process:

  1. Iterative Index Shifting:
    Lodash iterates over the array from index 0 to length - 1. It runs the predicate function against each item. Preserved elements are shifted leftward to the lowest available index, overwriting elements that matched the removal criteria. At the same time, the matching elements are copied into a separate return array.

  2. Truncation via the Native .length Property:
    Once iteration completes, the retained elements occupy indices 0 through newLength - 1. To remove the remaining trailing elements and update the collection's size, Lodash explicitly adjusts the array's native .length property:

    array.length = preservedCount;

How JavaScript Handles Synchronous .length Assignment

In JavaScript, setting an array's .length to a smaller value is a destructive operation that immediately deletes any elements located at indices greater than or equal to the new length.

Because _.remove executes synchronously on the call stack: