Lodash Array methods
What you’ll learn
- What to know before you start (see Prerequisites).
- How the Array group in Lodash maps to everyday tasks (chunking, deduping, set operations).
- When to prefer immutable helpers versus in-place mutators such as
pullorremove. - How to import Lodash efficiently in modern bundlers.
- Where to jump next for each
_.methodNametutorial on CodeToFun.
Prerequisites
JavaScript arrays, truthiness, first-class functions, and modules. Skip any row you already know; you can circle back from the method index.
- JavaScript arrays: literals (
[1, 2, 3]), zero-based indexes, and common instance methods such asmap,filter,slice, andsplice. - Values and truthiness: how
0,"",NaN,null, andundefinedbehave in conditions (needed forcompactand predicates). - First-class functions: passing functions as arguments (callbacks / predicates) because many Lodash APIs take an iteratee or comparator.
- Modules: either
importwith a bundler orrequirein Node.js, so the install examples match your project setup.
Key concepts
Lodash reuses a small vocabulary across the Array category. These four ideas appear in signatures, docs, and TypeScript typings; recognizing them makes every method faster to read.
Array & array-like
Most helpers expect a real array. Some also accept array-like values (indexed properties plus length). When unsure, normalize with Array.from(value) first.
Predicate
A function (value, index, collection) => boolean used by findIndex, remove, dropWhile, and similar APIs. Return truthy to “match” an element.
Iteratee
A function or shorthand (property path or key) that projects each value before comparison. Drives *By helpers such as uniqBy and differenceBy.
Comparator
A two-argument function, often (a, b) => number with the same sign convention as Array.prototype.sort, or an equality-style pair as documented per method. Used by *With helpers like unionWith.
Overview
Lodash array helpers cover reshaping nested lists, computing differences and intersections, stable deduplication, and safe indexing — all with predictable edge-case behavior across environments.
Reshape & zip
Use chunk, flatten*, and zip* when normalizing API payloads or pivoting columns.
Set operations
difference, intersection, union, and xor variants answer “which IDs changed?” style questions.
Search & slice
findIndex, sortedIndex*, and nth centralize bounds-safe lookups.
⚖️ Lodash vs native arrays
Modern JavaScript already covers many single-array flows. Lodash still shines when you need multi-array operations, stable edge cases, or less boilerplate for comparators and path-based projections.
| Situation | Prefer native | Consider Lodash |
|---|---|---|
| Map or filter one list | map, filter, optional chaining | Rarely needed unless you already depend on Lodash utilities nearby |
| Test membership against another list | Combine Set, includes, or loops | difference, intersection, without for clarity |
| Deduplicate by field or nested key | Map + manual bookkeeping | uniqBy with a path or iteratee |
| Chunk or unzip tabular data | Hand-rolled loops | chunk, zip, unzip |
| Binary-search style insert index | Implement bisect yourself | sortedIndex* family on pre-sorted arrays |
Install and import
Install the core package once per project, then import individual functions so bundlers can tree-shake unused helpers.
npm install lodash import chunk from "lodash/chunk";
import difference from "lodash/difference";
const rows = chunk([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]]
const onlyNew = difference([10, 20, 30], [20]);
// [10, 30] 🔄 Mutating vs new arrays
Most Lodash array functions return a new array and leave the source untouched. A smaller set mutates the array you pass in, which is fast but easy to miss during code review.
| Style | Typical methods | Rule of thumb |
|---|---|---|
| Returns new data | chunk, difference, uniq, take, slice | Safe to pipe through immutable UI state or Redux-style reducers. |
| Mutates in place | fill, pull, pullAll, pullAt, remove, reverse | Clone first (arr.slice() or [...arr]) if other code shares the same reference. |
When you intentionally want in-place updates (for example managing a buffer attached to a long-lived object), mutating helpers avoid allocating extra arrays.
Suggested learning path
If you are new to Lodash arrays, walk through this order inside your editor or Node REPL. Each step builds on the previous one.
- Reshape:
chunkandflattenfor grids and nested API payloads. - Cleanup:
compactanduniqfor removing noise before validation. - Set math:
differenceandintersectionfor comparing two ID lists. - Safe access:
nthandhead/lastinstead of manual length checks. - Conditional slices:
takeWhileanddropWhilefor prefix or suffix scanning.
💻 Environment and versions
- Lodash 4.x: the method list on this page matches the stable 4.x API surface used by most tutorials and
lodash@^4on npm. - Node.js and browsers: same package runs in both; choose ESM imports in bundlers and Vite, or
require('lodash/chunk')in CommonJS projects. - TypeScript: install
@types/lodashwhen you need typings for the full namespace import; per-method imports still benefit from those declarations.
Method index
Each row links to a focused tutorial when it exists in this site. URLs follow the /lodash/array/{method-kebab} pattern (for example /lodash/array/chunk).
| Method | What it does |
|---|---|
_.chunk() | Split an array into groups of length n. |
_.compact() | Remove falsy values (false, null, 0, "", undefined, NaN). |
_.concat() | Create a new array concatenating array with additional values. |
_.difference() | Values from the first array not present in the others. |
_.differenceBy() | Like difference, but values compared after invoking iteratee. |
_.differenceWith() | Like difference, but uses a comparator for equality. |
_.drop() | Drop n elements from the beginning. |
_.dropRight() | Drop n elements from the end. |
_.dropRightWhile() | Drop from the end while predicate returns truthy. |
_.dropWhile() | Drop from the start while predicate returns truthy. |
_.fill() | Fill all elements with a value between start and end. |
_.findIndex() | Index of the first element matching predicate. |
_.findLastIndex() | Index of the last element matching predicate. |
_.flatten() | Flatten one level of nested arrays. |
_.flattenDeep() | Recursively flatten until no nested arrays remain. |
_.flattenDepth() | Flatten up to depth levels. |
_.fromPairs() | Build an object from key-value pairs. |
_.head() | First element of an array (alias first). |
_.indexOf() | First index of value using SameValueZero. |
_.initial() | All but the last element. |
_.intersection() | Values common to all given arrays. |
_.intersectionBy() | Intersection after mapping each element with iteratee. |
_.intersectionWith() | Intersection using a comparator. |
_.join() | Join elements into a string with a separator. |
_.last() | Last element of an array. |
_.lastIndexOf() | Last index of value, searching from the end. |
_.nth() | Element at index n (supports negative indices). |
_.pull() | Remove all occurrences of given values in place. |
_.pullAll() | Like pull, but accepts an array of values to remove. |
_.pullAllBy() | Like pullAll, but values compared after iteratee. |
_.pullAllWith() | Like pullAll, but uses a comparator. |
_.pullAt() | Remove elements at indexes and return them. |
_.remove() | Remove elements matching predicate; returns removed elements. |
_.reverse() | Reverse array in place. |
_.slice() | Slice a portion of the array into a new array. |
_.sortedIndex() | Lowest index at which value should be inserted to keep sort order. |
_.sortedIndexBy() | Like sortedIndex, but compares iteratee(value). |
_.sortedIndexOf() | Like indexOf for sorted arrays. |
_.sortedLastIndex() | Highest index at which value should be inserted to keep sort order. |
_.sortedLastIndexBy() | Like sortedLastIndex with iteratee. |
_.sortedLastIndexOf() | Like lastIndexOf for sorted arrays. |
_.sortedUniq() | Unique values from a sorted array. |
_.sortedUniqBy() | Unique by iteratee from a sorted array. |
_.tail() | All but the first element. |
_.take() | Take n elements from the beginning. |
_.takeRight() | Take n elements from the end. |
_.takeRightWhile() | Take from the end while predicate is truthy. |
_.takeWhile() | Take from the start while predicate is truthy. |
_.union() | Unique values from all arrays combined. |
_.unionBy() | Union after mapping with iteratee. |
_.unionWith() | Union using a comparator. |
_.uniq() | Unique values preserving first occurrence order. |
_.uniqBy() | Unique by iteratee result. |
_.uniqWith() | Unique using a comparator for equality. |
_.unzip() | Inverse of zip: regroup tuples into arrays. |
_.unzipWith() | Like unzip, then apply iteratee to regrouped values. |
_.without() | Exclude given values from the array. |
_.xor() | Symmetric difference of arrays. |
_.xorBy() | Symmetric difference after iteratee. |
_.xorWith() | Symmetric difference with comparator. |
_.zip() | Group elements by index across arrays. |
_.zipObject() | Build an object from keys and values arrays. |
_.zipObjectDeep() | Like zipObject, with support for nested paths. |
_.zipWith() | Zip arrays and combine tuples with iteratee. |
Pitfalls to avoid
Surprise side effects
Callers sharing an array reference will see changes from pull, remove, or reverse; clone first when you need isolation.
Wrong comparator
*With helpers expect arity-2 comparators; mixing them up with iteratee-style callbacks yields empty or full arrays.
Skipped holes
Many Lodash algorithms treat holes differently than native map; prefer dense arrays for predictable results.
❓ FAQ
Summary
- Scope: Lodash array helpers complement native methods with multi-array math, iteratees, and comparators.
- Bundles: import per method to keep client payloads small.
- Next step: open Lodash _.chunk() or pick any row from the index table above.
Lodash head and first are aliases for the same function: returning the first element of an array.
9 people found this page helpful
