Lodash pullAt Return Value Explained
The _.pullAt method in the Lodash JavaScript library
removes elements from a given array at specified index positions and
mutates that original array. When invoked, _.pullAt returns
a new array containing the elements that were removed from the original
array, ordered according to the sequence of indices provided.
Return Value and Mutation Behavior
When you use _.pullAt(array, [indexes]), two distinct
actions occur:
- Array Mutation: The target array passed as the first argument is modified directly in place. The elements at the targeted indices are spliced out, shrinking the length of the original array.
- Returned Array: The method returns an entirely new array composed solely of the extracted (removed) elements.
If none of the specified indices exist within the array, the original
array remains unchanged, and _.pullAt returns an empty
array ([]).
Code Example
const _ = require('lodash');
// Define the initial array
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
// Remove elements at indices 1 and 3 ('banana' and 'date')
const removedElements = _.pullAt(fruits, [1, 3]);
// The return value contains the removed items
console.log(removedElements);
// Output: ['banana', 'date']
// The original array has been mutated in place
console.log(fruits);
// Output: ['apple', 'cherry', 'elderberry']Key Characteristics of the Return Value
- Index Sequence Preserved: The order of items in the
returned array reflects the order of the indices supplied in the
arguments, not necessarily their original order in the source array. For
example,
_.pullAt(arr, [3, 1])returns items from index 3 first, then index 1. - Separated References: The returned array is a new reference. Modifying the structure of the returned array does not further alter the original array, though any objects within it maintain their respective object references.
- Support for Multiple Arguments: You can pass
indices as an array (
[1, 3]) or as individual numeric arguments (_.pullAt(array, 1, 3)), and the return value will function identically in both cases.