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:
Iterative Index Shifting:
Lodash iterates over the array from index0tolength - 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.Truncation via the Native
.lengthProperty:
Once iteration completes, the retained elements occupy indices0throughnewLength - 1. To remove the remaining trailing elements and update the collection's size, Lodash explicitly adjusts the array's native.lengthproperty: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:
- Memory cleanup of discarded indices happens immediately upon length reassignment.
- Any read of
array.lengthdirectly following the_.removecall instantly returns the new count. - No subsequent garbage collection pass or deferred asynchronous task is required to reflect the new length.