乐闻世界logo
搜索文章和话题

What are the commonly used methods for Lodash collection operations? How to use them?

2月18日 21:59

Lodash provides rich collection operation methods. Here is a detailed answer about Lodash collection operations:

Lodash Collection Operations Overview

Lodash's collection operation methods can handle arrays and objects, providing rich data processing capabilities.

1. Collection Iteration Methods

_.forEach(collection, [iteratee])

Iterates over elements of collection and invokes iteratee for each element.

javascript
// Iterate over array _.forEach([1, 2], function(value) { console.log(value); }); // => Logs `1` then `2` // Iterate over object _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { console.log(key); }); // => Logs 'a' then 'b' // Alternative to using break var array = [1, 2, 3, 4, 5]; var shouldBreak = false; _.forEach(array, function(value) { if (value === 3) { shouldBreak = true; return false; // Returning false can interrupt iteration } console.log(value); });

_.forEachRight(collection, [iteratee])

Iterates over elements of collection from right to left.

javascript
_.forEachRight([1, 2], function(value) { console.log(value); }); // => Logs `2` then `1`

2. Collection Filtering Methods

_.filter(collection, [predicate])

Filters elements of collection that meet the predicate condition.

javascript
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false } ]; // Using function var result = _.filter(users, function(o) { return !o.active; }); // => objects for ['fred'] // Using object matching var result = _.filter(users, { 'age': 36, 'active': true }); // => objects for ['barney'] // Using property path var result = _.filter(users, ['active', false]); // => objects for ['fred'] // Using property value var result = _.filter(users, 'active'); // => objects for ['barney'] // Chaining var result = _.chain(users) .filter('active') .sortBy('age') .value();

_.reject(collection, [predicate])

Filters elements of collection that don't meet the predicate condition (opposite of filter).

javascript
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false } ]; var result = _.reject(users, function(o) { return !o.active; }); // => objects for ['barney']

3. Collection Mapping Methods

_.map(collection, [iteratee])

Creates an array of values by running each element in collection thru iteratee.

javascript
// Map array function square(n) { return n * n; } _.map([4, 8], square); // => [16, 64] // Map object _.map({ 'a': 4, 'b': 8 }, square); // => [16, 64] // Using object property var users = [ { 'user': 'barney' }, { 'user': 'fred' } ]; _.map(users, 'user'); // => ['barney', 'fred'] // Chaining var result = _.chain(users) .map('user') .map(_.upperFirst) .value(); // => ['Barney', 'Fred']

_.flatMap(collection, [iteratee])

Creates a flattened array of values by running each element in collection thru iteratee and flattening the mapped results.

javascript
function duplicate(n) { return [n, n]; } _.flatMap([1, 2], duplicate); // => [1, 1, 2, 2] // Real application: Expand nested arrays var data = [ { id: 1, tags: ['javascript', 'react'] }, { id: 2, tags: ['vue', 'typescript'] } ]; var allTags = _.flatMap(data, 'tags'); // => ['javascript', 'react', 'vue', 'typescript']

_.flatMapDeep(collection, [iteratee])

Recursively flattens mapped results.

javascript
function duplicate(n) { return [[[n, n]]]; } _.flatMapDeep([1, 2], duplicate); // => [1, 1, 2, 2]

4. Collection Finding Methods

_.find(collection, [predicate], [fromIndex])

Iterates over elements of collection, returning the first element predicate returns truthy for.

javascript
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'pebbles', 'age': 1, 'active': true } ]; // Using function var result = _.find(users, function(o) { return o.age < 40; }); // => object for 'barney' // Using object matching var result = _.find(users, { 'age': 1, 'active': true }); // => object for 'pebbles' // Using property path var result = _.find(users, ['active', false]); // => object for 'fred' // Using property value var result = _.find(users, 'active'); // => object for 'barney' // Specify starting index var result = _.find(users, 'active', 1); // => object for 'pebbles'

_.findLast(collection, [predicate], [fromIndex])

Iterates over elements of collection from right to left, returning the first element predicate returns truthy for.

javascript
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'pebbles', 'age': 1, 'active': true } ]; var result = _.findLast(users, function(o) { return o.age < 40; }); // => object for 'pebbles'

5. Collection Grouping Methods

_.groupBy(collection, [iteratee])

Creates an object composed of keys generated from the results of running each element of collection thru iteratee.

javascript
// Group by function _.groupBy([6.1, 4.2, 6.3], Math.floor); // => { '4': [4.2], '6': [6.1, 6.3] } // Group by property _.groupBy(['one', 'two', 'three'], 'length'); // => { '3': ['one', 'two'], '5': ['three'] } // Group by object property var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'pebbles', 'age': 36, 'active': true } ]; _.groupBy(users, 'age'); // => { '36': [objects for 'barney' and 'pebbles'], '40': [object for 'fred'] } // Multi-condition grouping _.groupBy(users, function(user) { return user.active ? 'active' : 'inactive'; }); // => { 'active': [objects for 'barney' and 'pebbles'], 'inactive': [object for 'fred'] }

_.keyBy(collection, [iteratee])

Creates an object composed of keys generated from the results of running each element of collection thru iteratee.

javascript
var array = [ { 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 } ]; _.keyBy(array, function(o) { return String.fromCharCode(o.code); }); // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } _.keyBy(array, 'dir'); // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }

_.countBy(collection, [iteratee])

Creates an object composed of keys generated from the results of running each element of collection thru iteratee, with values being the count of occurrences.

javascript
_.countBy([6.1, 4.2, 6.3], Math.floor); // => { '4': 1, '6': 2 } _.countBy(['one', 'two', 'three'], 'length'); // => { '3': 2, '5': 1 } // Real application: Count tag occurrences var posts = [ { tags: ['javascript', 'react'] }, { tags: ['vue', 'javascript'] }, { tags: ['react', 'typescript'] } ]; var allTags = _.flatMap(posts, 'tags'); var tagCounts = _.countBy(allTags); // => { javascript: 2, react: 2, vue: 1, typescript: 1 }

6. Collection Sorting Methods

_.sortBy(collection, [iteratees])

Creates an array of elements, sorted in ascending order by the results of running each element through iteratees.

javascript
var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'barney', 'age': 34 } ]; // Single condition sort _.sortBy(users, function(o) { return o.user; }); // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] _.sortBy(users, ['user', 'age']); // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] // Using property path _.sortBy(users, ['user', 'age']); // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] // Descending sort _.sortBy(users, ['user', 'age']).reverse();

_.orderBy(collection, [iteratees], [orders])

This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by.

javascript
var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'barney', 'age': 34 } ]; _.orderBy(users, ['user', 'age'], ['asc', 'desc']); // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]

7. Collection Statistics Methods

_.size(collection)

Gets the size of collection.

javascript
_.size([1, 2, 3]); // => 3 _.size({ 'a': 1, 'b': 2 }); // => 2 _.size('pebbles'); // => 7

_.sample(collection)

Gets a random element from collection.

javascript
_.sample([1, 2, 3, 4]); // => 2 _.sample({ 'a': 1, 'b': 2 }); // => 1

_.sampleSize(collection, [n=1])

Gets n random elements at unique keys from collection up to the size of collection.

javascript
_.sampleSize([1, 2, 3], 2); // => [3, 1] _.sampleSize([1, 2, 3], 4); // => [2, 3, 1]

_.shuffle(collection)

Creates an array of shuffled values.

javascript
_.shuffle([1, 2, 3, 4]); // => [4, 1, 3, 2]

8. Collection Reduction Methods

_.reduce(collection, [iteratee], [accumulator])

Reduces collection to a value which is the accumulated result of running each element in collection thru iteratee.

javascript
// Array reduction _.reduce([1, 2], function(sum, n) { return sum + n; }, 0); // => 3 // Object reduction _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { (result[value] || (result[value] = [])).push(key); return result; }, {}); // => { '1': ['a', 'c'], '2': ['b'] }

_.reduceRight(collection, [iteratee], [accumulator])

This method is like _.reduce except that it iterates over elements of collection from right to left.

javascript
var array = [[0, 1], [2, 3], [4, 5]]; _.reduceRight(array, function(flattened, other) { return flattened.concat(other); }, []); // => [4, 5, 2, 3, 0, 1]

9. Collection Checking Methods

_.every(collection, [predicate])

Checks if predicate returns truthy for all elements of collection.

javascript
_.every([true, 1, null, 'yes'], Boolean); // => false var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': true } ]; _.every(users, { 'user': 'barney', 'active': true }); // => false _.every(users, ['active', true]); // => true _.every(users, 'active'); // => true

_.some(collection, [predicate])

Checks if predicate returns truthy for any element of collection.

javascript
_.some([null, 0, 'yes', false], Boolean); // => true var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false } ]; _.some(users, { 'user': 'barney', 'active': false }); // => false _.some(users, ['active', false]); // => true _.some(users, 'active'); // => true

_.includes(collection, value, [fromIndex=0])

Checks if value is in collection.

javascript
_.includes([1, 2, 3], 1); // => true _.includes([1, 2, 3], 1, 2); // => false _.includes({ 'a': 1, 'b': 2 }, 1); // => true _.includes('abcd', 'bc'); // => true

10. Collection Conversion Methods

_.toArray(collection)

Converts collection to array.

javascript
_.toArray({ 'a': 1, 'b': 2 }); // => [1, 2] _.toArray('abc'); // => ['a', 'b', 'c'] _.toArray(1); // => [] _.toArray(null); // => []

_.toPlainObject(value)

Converts value to a plain object flattening inherited enumerable string keyed properties of value to own properties of the plain object.

javascript
function Foo() { this.a = 1; } Foo.prototype.b = 2; _.toPlainObject(new Foo); // => { 'a': 1 }

Real-World Application Examples

Data Analysis and Statistics

javascript
class DataAnalyzer { static analyzeSales(salesData) { return { totalSales: _.sumBy(salesData, 'amount'), averageSale: _.meanBy(salesData, 'amount'), salesByProduct: _.groupBy(salesData, 'product'), topSellingProducts: _.chain(salesData) .groupBy('product') .mapValues(items => ({ product: items[0].product, totalAmount: _.sumBy(items, 'amount'), count: items.length })) .values() .orderBy('totalAmount', 'desc') .take(5) .value(), salesByMonth: _.chain(salesData) .groupBy(item => item.date.substring(0, 7)) .mapValues(items => ({ month: items[0].date.substring(0, 7), totalAmount: _.sumBy(items, 'amount'), count: items.length })) .values() .orderBy('month') .value() }; } } const salesData = [ { date: '2024-01-01', product: 'A', amount: 100 }, { date: '2024-01-02', product: 'B', amount: 150 }, { date: '2024-01-03', product: 'A', amount: 200 }, { date: '2024-02-01', product: 'C', amount: 300 } ]; const analysis = DataAnalyzer.analyzeSales(salesData);

User Data Processing

javascript
class UserProcessor { static processUsers(users) { return _.chain(users) .filter(user => user.active) .map(user => ({ id: user.id, name: _.upperFirst(user.name), email: _.toLower(user.email), role: user.role || 'user', createdAt: new Date(user.created_at) })) .sortBy('createdAt') .groupBy('role') .mapValues(items => ({ count: items.length, users: items })) .value(); } static findUserByEmail(users, email) { return _.find(users, { email: _.toLower(email) }); } static getUsersByRole(users, role) { return _.filter(users, { role }); } static getActiveUsers(users) { return _.filter(users, 'active'); } static getUserStats(users) { return { total: users.length, active: _.filter(users, 'active').length, inactive: _.reject(users, 'active').length, byRole: _.countBy(users, 'role') }; } }

Summary

Lodash's collection operation methods include:

  1. Iteration Methods:

    • _.forEach() - Iterate over collection
    • _.forEachRight() - Iterate from right to left
  2. Filtering Methods:

    • _.filter() - Filter elements that meet condition
    • _.reject() - Filter elements that don't meet condition
  3. Mapping Methods:

    • _.map() - Map elements
    • _.flatMap() - Map and flatten
    • _.flatMapDeep() - Recursively map and flatten
  4. Finding Methods:

    • _.find() - Find first element that meets condition
    • _.findLast() - Find from right to left
  5. Grouping Methods:

    • _.groupBy() - Group elements
    • _.keyBy() - Convert to object
    • _.countBy() - Count occurrences
  6. Sorting Methods:

    • _.sortBy() - Sort elements
    • _.orderBy() - Sort with specified direction
  7. Statistics Methods:

    • _.size() - Get size
    • _.sample() - Get random element
    • _.sampleSize() - Get n random elements
    • _.shuffle() - Shuffle randomly
  8. Reduction Methods:

    • _.reduce() - Reduce collection
    • _.reduceRight() - Reduce from right to left
  9. Checking Methods:

    • _.every() - Check all elements
    • _.some() - Check if any element
    • _.includes() - Check if contains
  10. Conversion Methods:

    • _.toArray() - Convert to array
    • _.toPlainObject() - Convert to plain object

These methods can be used individually or combined through chaining, providing powerful data processing capabilities.

标签:Lodash