Lodash - Collection
Lodash - Collection Methods
Section titled “Lodash - Collection Methods”Lodash excels at working with collections, which include both arrays and objects. Its collection functions provide powerful and convenient ways to iterate, filter, group, sort, and transform data, often with more flexibility than native JavaScript methods.
A key feature is Lodash’s ability to accept various ‘iteratee’ shorthands (function, string property name, object for matching, or array pair for matching) simplifying common operations.
Core Collection Methods
Section titled “Core Collection Methods”While native Array methods like map, filter, reduce, find, some, every, and includes are powerful, Lodash offers equivalents that work on both arrays and object values, along with additional useful methods:
| Method & Syntax | Description & Key Features |
|---|---|
| forEach / each .forEach(collection, [iteratee=.identity]) | Iterates over elements of collection, executing iteratee for each element. Works on arrays and objects. Native equivalent: Array.prototype.forEach (arrays only), for...in or Object.keys/values/entries().forEach (objects). |
| map .map(collection, [iteratee=.identity]) | Creates an array of values by running each element in collection thru iteratee. Works on arrays and objects (maps values). Native equivalent: Array.prototype.map (arrays only). |
| filter .filter(collection, [predicate=.identity]) | Iterates over elements of collection, returning an array of all elements predicate returns truthy for. Works on arrays and objects (filters based on values). Native equivalent: Array.prototype.filter (arrays only). |
| reject .reject(collection, [predicate=.identity]) | The opposite of _.filter; returns elements predicate returns falsey for. |
| find .find(collection, [predicate=.identity], [fromIndex=0]) | Iterates over elements of collection, returning the first element predicate returns truthy for. Works on arrays and objects. Native equivalent: Array.prototype.find (arrays only). |
| reduce .reduce(collection, [iteratee=.identity], [accumulator]) | Reduces collection to a single value by running each element thru iteratee. Works on arrays and objects. Native equivalent: Array.prototype.reduce (arrays only). |
| every .every(collection, [predicate=.identity]) | Checks if predicate returns truthy for all elements of collection. Works on arrays and objects. Native equivalent: Array.prototype.every (arrays only). |
| some .some(collection, [predicate=.identity]) | Checks if predicate returns truthy for any element of collection. Works on arrays and objects. Native equivalent: Array.prototype.some (arrays only). |
| includes _.includes(collection, value, [fromIndex=0]) | Checks if value is in collection. Uses SameValueZero for equality comparisons. Works on arrays, objects (checks values), and strings. Native equivalent: Array.prototype.includes, String.prototype.includes. |
| groupBy .groupBy(collection, [iteratee=.identity]) | Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is an array of elements responsible for generating the key. |
| keyBy .keyBy(collection, [iteratee=.identity]) | Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the last element responsible for generating the key. |
| orderBy .orderBy(collection, [iteratees=[.identity]], [orders]) | Sorts elements of collection based on iteratees and corresponding orders (‘asc’ or ‘desc’). More powerful than Array.prototype.sort as it allows multiple sorting criteria and handles complex data types robustly. |
| sortBy .sortBy(collection, [iteratees=[.identity]]) | Simpler version of orderBy for ascending order sorting based on one or more criteria. |
| partition .partition(collection, [predicate=.identity]) | Creates an array of elements split into two groups, the first containing elements predicate returns truthy for, the second containing the remaining elements. |
| sample _.sample(collection) | Gets a random element from collection. |
| sampleSize _.sampleSize(collection, [n=1]) | Gets n random elements from collection. |
| shuffle _.shuffle(collection) | Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. |
| size _.size(collection) | Gets the size of collection by returning its length for array-like values or the number of own enumerable string keyed properties for objects. Native equivalent: Array.prototype.length, Object.keys(obj).length. |
| flatMap .flatMap(collection, [iteratee=.identity]) | Creates a flattened array of values by running each element in collection thru iteratee and flattening the mapped results. Native equivalent: Array.prototype.flatMap (arrays only). |
| flatMapDeep .flatMapDeep(collection, [iteratee=.identity]) | Like _.flatMap, but recursively flattens the mapped results. |
| flatMapDepth .flatMapDepth(collection, [iteratee=.identity], [depth=1]) | Like _.flatMap, but flattens the mapped results up to depth levels. |
Iteratee Shorthands
Section titled “Iteratee Shorthands”Many Lodash collection methods accept shorthand syntax for the iteratee or predicate argument:
- String:
_.map(users, 'name')(gets the ‘name’ property) - Object:
_.filter(users, { active: true })(matches objects withactive: true) - Array:
_.find(users, ['name', 'Alice'])(matches objects wherenameis ‘Alice’)
Example: Grouping and Mapping
Section titled “Example: Grouping and Mapping”import _ from 'lodash-es';
const users = [ { 'name': 'Alice', 'role': 'admin', 'active': true }, { 'name': 'Bob', 'role': 'editor', 'active': true }, { 'name': 'Charlie', 'role': 'editor', 'active': false }, { 'name': 'David', 'role': 'admin', 'active': true }];
// Group users by roleconst usersByRole = _.groupBy(users, 'role');// usersByRole: { admin: [...], editor: [...] }
// Get names of active usersconst activeUserNames = _(users) .filter('active') // Shorthand: { active: true } .map('name') // Shorthand: user => user.name .value(); // Execute the chain// activeUserNames: ['Alice', 'Bob', 'David']
// Create an object mapping user names to their rolesconst nameToRoleMap = _.keyBy(users, 'name');// nameToRoleMap: { Alice: { name: 'Alice', ... }, Bob: { ... }, ... }const simpleMap = _.mapValues(nameToRoleMap, 'role');// simpleMap: { Alice: 'admin', Bob: 'editor', Charlie: 'editor', David: 'admin' }
console.log('Users by Role:', usersByRole);console.log('Active User Names:', activeUserNames);console.log('Role Map:', simpleMap);Lodash collection methods provide a concise and powerful way to manipulate data structures common in web development, data analysis, and general scripting tasks.