- Spec files
npm-lodash
Describes: pkg:npm/lodash@4.5.x
- Description
- Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
- Author
- tessl
- Last updated
collection-methods.md docs/
1# Collection Methods23Powerful iteration and transformation methods that work with arrays, objects, and other collections. These methods provide the foundation for data processing and functional programming patterns.45## Capabilities67### Core Iteration89#### forEach10Iterates over elements of collection and invokes iteratee for each element.1112```javascript { .api }13/**14* Iterates over elements of collection and invokes iteratee for each element15* @param collection - The collection to iterate over16* @param iteratee - The function invoked per iteration17* @returns Returns collection18*/19function forEach(collection, iteratee);2021/**22* Like forEach but iterates over elements from right to left23* @param collection - The collection to iterate over24* @param iteratee - The function invoked per iteration25* @returns Returns collection26*/27function forEachRight(collection, iteratee);2829// Aliases30const each = forEach;31const eachRight = forEachRight;32```3334#### map35Creates an array of values by running each element in collection through iteratee.3637```javascript { .api }38/**39* Creates an array of values by running each element in collection through iteratee40* @param collection - The collection to iterate over41* @param iteratee - The function invoked per iteration42* @returns Returns the new mapped array43*/44function map(collection, iteratee);45```4647### Filtering & Finding4849#### filter50Iterates over elements of collection, returning an array of all elements predicate returns truthy for.5152```javascript { .api }53/**54* Iterates over elements of collection, returning an array of all elements predicate returns truthy for55* @param collection - The collection to iterate over56* @param predicate - The function invoked per iteration57* @returns Returns the new filtered array58*/59function filter(collection, predicate);6061/**62* The opposite of filter; creates an array of elements predicate returns falsey for63* @param collection - The collection to iterate over64* @param predicate - The function invoked per iteration65* @returns Returns the new filtered array66*/67function reject(collection, predicate);68```6970#### find71Iterates over elements of collection, returning the first element predicate returns truthy for.7273```javascript { .api }74/**75* Iterates over elements of collection, returning the first element predicate returns truthy for76* @param collection - The collection to iterate over77* @param predicate - The function invoked per iteration78* @param fromIndex - The index to search from79* @returns Returns the matched element, else undefined80*/81function find(collection, predicate, fromIndex = 0);8283/**84* Like find except that it iterates over elements from right to left85* @param collection - The collection to iterate over86* @param predicate - The function invoked per iteration87* @param fromIndex - The index to search from88* @returns Returns the matched element, else undefined89*/90function findLast(collection, predicate, fromIndex = collection.length - 1);91```9293### Testing & Validation9495#### every & some96Tests whether elements pass a predicate test.9798```javascript { .api }99/**100* Checks if predicate returns truthy for all elements of collection101* @param collection - The collection to iterate over102* @param predicate - The function invoked per iteration103* @returns Returns true if all elements pass the predicate check, else false104*/105function every(collection, predicate);106107/**108* Checks if predicate returns truthy for any element of collection109* @param collection - The collection to iterate over110* @param predicate - The function invoked per iteration111* @returns Returns true if any element passes the predicate check, else false112*/113function some(collection, predicate);114```115116#### includes117Checks if value is in collection.118119```javascript { .api }120/**121* Checks if value is in collection using SameValueZero for equality comparisons122* @param collection - The collection to inspect123* @param value - The value to search for124* @param fromIndex - The index to search from125* @returns Returns true if value is found, else false126*/127function includes(collection, value, fromIndex = 0);128```129130### Aggregation & Reduction131132#### reduce133Reduces collection to a value which is the accumulated result of running each element through iteratee.134135```javascript { .api }136/**137* Reduces collection to a value which is the accumulated result of running each element through iteratee138* @param collection - The collection to iterate over139* @param iteratee - The function invoked per iteration140* @param accumulator - The initial value141* @returns Returns the accumulated value142*/143function reduce(collection, iteratee, accumulator);144145/**146* Like reduce except that it iterates over elements from right to left147* @param collection - The collection to iterate over148* @param iteratee - The function invoked per iteration149* @param accumulator - The initial value150* @returns Returns the accumulated value151*/152function reduceRight(collection, iteratee, accumulator);153```154155#### size156Gets the size of collection by returning its length for array-like values or the number of own enumerable string keyed properties for objects.157158```javascript { .api }159/**160* Gets the size of collection161* @param collection - The collection to inspect162* @returns Returns the collection size163*/164function size(collection);165```166167### Grouping & Organization168169#### groupBy170Creates an object composed of keys generated from the results of running each element through iteratee.171172```javascript { .api }173/**174* Creates an object composed of keys generated from the results of running each element through iteratee175* @param collection - The collection to iterate over176* @param iteratee - The iteratee to transform keys177* @returns Returns the composed aggregate object178*/179function groupBy(collection, iteratee);180181/**182* Creates an object composed of keys generated from the results of running each element through iteratee183* @param collection - The collection to iterate over184* @param iteratee - The iteratee to transform keys185* @returns Returns the composed aggregate object186*/187function keyBy(collection, iteratee);188189/**190* Creates an object composed of keys generated from the results of running each element through iteratee191* @param collection - The collection to iterate over192* @param iteratee - The iteratee to transform keys193* @returns Returns the composed aggregate object194*/195function countBy(collection, iteratee);196```197198#### partition199Creates an array of two arrays, the first of which contains elements predicate returns truthy for.200201```javascript { .api }202/**203* Creates an array of two arrays, the first of which contains elements predicate returns truthy for204* @param collection - The collection to iterate over205* @param predicate - The function invoked per iteration206* @returns Returns the array of grouped elements207*/208function partition(collection, predicate);209```210211### Sorting212213#### sortBy214Creates an array of elements, sorted in ascending order by the results of running each element through each iteratee.215216```javascript { .api }217/**218* Creates an array of elements, sorted in ascending order by the results of running each element through each iteratee219* @param collection - The collection to iterate over220* @param iteratees - The iteratees to sort by221* @returns Returns the new sorted array222*/223function sortBy(collection, ...iteratees);224225/**226* Creates an array of elements, sorted by iteratees in orders227* @param collection - The collection to iterate over228* @param iteratees - The iteratees to sort by229* @param orders - The sort orders of iteratees230* @returns Returns the new sorted array231*/232function orderBy(collection, iteratees, orders);233```234235### Sampling236237#### sample238Gets a random element from collection.239240```javascript { .api }241/**242* Gets a random element from collection243* @param collection - The collection to sample244* @returns Returns the random element245*/246function sample(collection);247248/**249* Gets n random elements at unique keys from collection up to the size of collection250* @param collection - The collection to sample251* @param n - The number of elements to sample252* @returns Returns the random elements253*/254function sampleSize(collection, n = 1);255256/**257* Creates an array of shuffled values, using a version of the Fisher-Yates shuffle258* @param collection - The collection to shuffle259* @returns Returns the new shuffled array260*/261function shuffle(collection);262```263264### FlatMap Operations265266#### flatMap267Creates a flattened array of values by running each element through iteratee and flattening the mapped results.268269```javascript { .api }270/**271* Creates a flattened array of values by running each element through iteratee and flattening the mapped results272* @param collection - The collection to iterate over273* @param iteratee - The function invoked per iteration274* @returns Returns the new flattened array275*/276function flatMap(collection, iteratee);277278/**279* Like flatMap but recursively flattens the mapped results280* @param collection - The collection to iterate over281* @param iteratee - The function invoked per iteration282* @returns Returns the new flattened array283*/284function flatMapDeep(collection, iteratee);285286/**287* Like flatMap but recursively flattens the mapped results up to depth times288* @param collection - The collection to iterate over289* @param iteratee - The function invoked per iteration290* @param depth - The maximum recursion depth291* @returns Returns the new flattened array292*/293function flatMapDepth(collection, iteratee, depth = 1);294```295296### Method Invocation297298#### invokeMap299Invokes the method at path of each element in collection.300301```javascript { .api }302/**303* Invokes the method at path of each element in collection304* @param collection - The collection to iterate over305* @param path - The path of the method to invoke306* @param args - The arguments to invoke each method with307* @returns Returns the array of results308*/309function invokeMap(collection, path, ...args);310```311312## Iteratee Shorthand313314Lodash collection methods support several shorthand syntaxes for common operations:315316```javascript { .api }317// Property shorthand - gets property value318map(users, 'name'); // → ['John', 'Jane', 'Bob']319320// Path shorthand - gets nested property value321map(users, 'profile.age'); // → [30, 25, 35]322323// Object shorthand - partial deep comparison324filter(users, { active: true }); // → users where active === true325filter(users, { role: 'admin' }); // → admin users326327// Array shorthand - [path, value] for matchesProperty328filter(users, ['role', 'admin']); // → admin users329```330331## Usage Examples332333```javascript334import {335map, filter, find, groupBy, reduce, sortBy,336every, some, partition, sample, flatMap337} from "lodash";338339const users = [340{ name: 'John', age: 30, role: 'admin', active: true },341{ name: 'Jane', age: 25, role: 'user', active: true },342{ name: 'Bob', age: 35, role: 'user', active: false },343{ name: 'Alice', age: 28, role: 'admin', active: true }344];345346// Transform collections347const names = map(users, 'name');348// Result: ['John', 'Jane', 'Bob', 'Alice']349350const adults = filter(users, user => user.age >= 30);351// Result: [{ name: 'John', age: 30, ... }, { name: 'Bob', age: 35, ... }]352353// Find elements354const admin = find(users, { role: 'admin' });355// Result: { name: 'John', age: 30, role: 'admin', active: true }356357// Group data358const byRole = groupBy(users, 'role');359// Result: { admin: [...], user: [...] }360361// Aggregate data362const totalAge = reduce(users, (sum, user) => sum + user.age, 0);363// Result: 118364365// Sort collections366const byAge = sortBy(users, 'age');367// Result: users sorted by age ascending368369// Test collections370const allActive = every(users, 'active'); // false371const someActive = some(users, 'active'); // true372373// Split collections374const [active, inactive] = partition(users, 'active');375// active: users with active: true, inactive: users with active: false376377// Sample collections378const randomUser = sample(users); // Random user379const twoUsers = sampleSize(users, 2); // Two random users380381// FlatMap operations382const tags = [383{ name: 'Post 1', tags: ['js', 'web'] },384{ name: 'Post 2', tags: ['react', 'js'] }385];386const allTags = flatMap(tags, 'tags');387// Result: ['js', 'web', 'react', 'js']388389// Complex operations390const activeAdminNames = users391|> filter(%, { active: true })392|> filter(%, { role: 'admin' })393|> map(%, 'name');394// Using pipeline operator for clarity395```