Lodash pullAt with Out of Bounds Indices
In Lodash, the _.pullAt method removes elements from an
array at specified indices and returns an array containing the pulled
elements. When the provided array of indices consists entirely of
out-of-bounds numbers, _.pullAt returns an array containing
undefined for each given index, while leaving the original
target array unmodified.
Return Value Behavior
Lodash determines the returned values by mapping over the supplied
indices and retrieving the corresponding value from the target array
before performing any mutation. In JavaScript, accessing an index that
does not exist on an array yields undefined.
Consequently, if you provide \(N\)
out-of-bounds indices, _.pullAt returns an array of length
\(N\) where every element is
undefined.
const _ = require('lodash');
const numbers = [10, 20, 30];
// Providing purely out-of-bounds positive indices
const result = _.pullAt(numbers, [5, 8]);
console.log(result);
// Output: [undefined, undefined]
// Providing negative indices (which are also out-of-bounds in Lodash pullAt)
const negativeResult = _.pullAt(numbers, [-1, -4]);
console.log(negativeResult);
// Output: [undefined, undefined]Impact on the Original Array
Under normal circumstances, _.pullAt mutates the input
array by removing elements at valid positions. However, Lodash includes
internal index validation using its isIndex check, which
requires an index to be an integer within the range
0 <= index < length.
Because out-of-bounds and negative indices fail this check, no elements are spliced from the target array. The source array retains its original values and length:
const items = ['a', 'b', 'c'];
_.pullAt(items, [10, 20]);
console.log(items);
// Output: ['a', 'b', 'c']Summary
When passed purely out-of-bounds indices, _.pullAt
will:
- Return a new array of matching length populated entirely with
undefined. - Leave the original array completely unchanged.