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

What are the commonly used array operation methods in Lodash? Please provide examples of their usage

2月18日 21:59

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

Common Lodash Array Operation Methods

1. Array Creation and Transformation

_.chunk(array, [size=1])

Splits an array into chunks of a specified size.

javascript
_.chunk(['a', 'b', 'c', 'd'], 2); // => [['a', 'b'], ['c', 'd']] _.chunk(['a', 'b', 'c', 'd'], 3); // => [['a', 'b', 'c'], ['d']] // Real application: Paginated display function paginate(items, pageSize) { return _.chunk(items, pageSize); } const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const pages = paginate(items, 3); // => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

_.compact(array)

Removes falsy values from an array (false, null, 0, "", undefined, NaN).

javascript
_.compact([0, 1, false, 2, '', 3]); // => [1, 2, 3] // Real application: Clean form data function cleanFormData(formData) { return _.compact(formData); } const formData = ['', 'John', null, 'john@example.com', undefined]; const cleaned = cleanFormData(formData); // => ['John', 'john@example.com']

_.concat(array, [values])

Concatenates an array and values into a new array.

javascript
var array = [1]; var other = _.concat(array, 2, [3], [[4]]); console.log(other); // => [1, 2, 3, [4]] // Real application: Merge multiple arrays function mergeArrays(...arrays) { return _.concat([], ...arrays); } const result = mergeArrays([1, 2], [3, 4], [5, 6]); // => [1, 2, 3, 4, 5, 6]

2. Array Filtering and Finding

_.difference(array, [values])

Creates a new array of values not included in the given array.

javascript
_.difference([2, 1], [2, 3]); // => [1] _.difference([1, 2, 3, 4, 5], [2, 4]); // => [1, 3, 5] // Real application: Get new items function getNewItems(currentItems, previousItems) { return _.difference(currentItems, previousItems); } const current = [1, 2, 3, 4, 5]; const previous = [1, 2, 3]; const newItems = getNewItems(current, previous); // => [4, 5]

_.differenceBy(array, [values], [iteratee])

Similar to _.difference, but accepts an iteratee function.

javascript
_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // => [1.2] // Real application: Find differences based on object properties const users1 = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]; const users2 = [ { id: 1, name: 'Alice' }, { id: 3, name: 'Charlie' } ]; const newUsers = _.differenceBy(users2, users1, 'id'); // => [{ id: 3, name: 'Charlie' }]

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

Finds the first element in the array that satisfies the condition.

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

_.filter(collection, [predicate])

Iterates over a collection and returns an array of elements that satisfy the condition.

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

3. Array Deduplication

_.uniq(array)

Creates a duplicate-free version of an array.

javascript
_.uniq([2, 1, 2]); // => [2, 1] // Real application: Get unique values function getUniqueValues(array) { return _.uniq(array); } const values = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]; const unique = getUniqueValues(values); // => [1, 2, 3, 4]

_.uniqBy(array, [iteratee])

Deduplicates based on the result of the iteratee function.

javascript
_.uniqBy([2.1, 1.2, 2.3], Math.floor); // => [2.1, 1.2] // Real application: Deduplicate by object property const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice' } ]; const uniqueUsers = _.uniqBy(users, 'id'); // => [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]

_.uniqWith(array, [comparator])

Deduplicates using a comparison function.

javascript
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; _.uniqWith(objects, _.isEqual); // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

4. Array Sorting

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

Sorts a collection in a specified order.

javascript
var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 34 }, { 'user': 'fred', 'age': 40 }, { 'user': 'barney', 'age': 36 } ]; _.orderBy(users, ['user', 'age'], ['asc', 'desc']); // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] // Real application: Multi-field sorting function sortUsers(users) { return _.orderBy(users, ['lastName', 'firstName'], ['asc', 'asc']); } const users = [ { firstName: 'John', lastName: 'Doe' }, { firstName: 'Jane', lastName: 'Doe' }, { firstName: 'John', lastName: 'Smith' } ]; const sorted = sortUsers(users); // => [ // { firstName: 'Jane', lastName: 'Doe' }, // { firstName: 'John', lastName: 'Doe' }, // { firstName: 'John', lastName: 'Smith' } // ]

_.sortBy(collection, [iteratees])

Sorts a collection in ascending order.

javascript
var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'barney', 'age': 34 } ]; _.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]]

5. Array Transformation

_.map(collection, [iteratee])

Creates an array containing the results of processing each element in the collection through an iteratee function.

javascript
function square(n) { return n * n; } _.map([4, 8], square); // => [16, 64] _.map({ 'a': 4, 'b': 8 }, square); // => [16, 64] (iteration order is not guaranteed) var users = [ { 'user': 'barney' }, { 'user': 'fred' } ]; _.map(users, 'user'); // => ['barney', 'fred']

_.flatMap(collection, [iteratee])

Creates a flattened array containing the results of processing each element in the collection through an iteratee function.

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

_.flatMapDeep(collection, [iteratee])

Similar to _.flatMap, but recursively flattens.

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

6. Array Grouping

_.groupBy(collection, [iteratee])

Groups a collection based on the result of the iteratee function.

javascript
_.groupBy([6.1, 4.2, 6.3], Math.floor); // => { '4': [4.2], '6': [6.1, 6.3] } _.groupBy(['one', 'two', 'three'], 'length'); // => { '3': ['one', 'two'], '5': ['three'] } // Real application: Group by category const products = [ { id: 1, name: 'Product A', category: 'Electronics' }, { id: 2, name: 'Product B', category: 'Clothing' }, { id: 3, name: 'Product C', category: 'Electronics' } ]; const grouped = _.groupBy(products, 'category'); // => { // 'Electronics': [ // { id: 1, name: 'Product A', category: 'Electronics' }, // { id: 3, name: 'Product C', category: 'Electronics' } // ], // 'Clothing': [ // { id: 2, name: 'Product B', category: 'Clothing' } // ] // }

_.keyBy(collection, [iteratee])

Creates an object with keys as the iteratee results and values as the corresponding elements.

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 } }

7. Array Slicing

_.take(array, [n=1])

Takes n elements from the beginning of an array.

javascript
_.take([1, 2, 3]); // => [1] _.take([1, 2, 3], 2); // => [1, 2] _.take([1, 2, 3], 5); // => [1, 2, 3] _.take([1, 2, 3], 0); // => []

_.takeRight(array, [n=1])

Takes n elements from the end of an array.

javascript
_.takeRight([1, 2, 3]); // => [3] _.takeRight([1, 2, 3], 2); // => [2, 3] _.takeRight([1, 2, 3], 5); // => [1, 2, 3]

_.slice(array, [start=0], [end=array.length])

Slices a portion of an array.

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

8. Array Checking

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

Checks if a collection contains a value.

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

_.some(collection, [predicate])

Checks if any element in the collection satisfies the condition.

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

_.every(collection, [predicate])

Checks if all elements in the collection satisfy the condition.

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

Real-World Application Examples

Data Processing Pipeline

javascript
class DataProcessor { constructor(data) { this.data = data; } process() { return _.chain(this.data) .filter(item => item.active) .map(item => this.transformItem(item)) .uniqBy('id') .orderBy('createdAt', 'desc') .take(10) .value(); } transformItem(item) { return { id: item.id, name: _.upperFirst(item.name), value: _.round(item.value, 2) }; } }

Table Data Processing

javascript
function processTableData(rawData) { return _.chain(rawData) .filter(row => !_.isEmpty(row)) .map(row => _.mapValues(row, value => _.trim(value))) .uniqBy('id') .orderBy(['category', 'name'], ['asc', 'asc']) .value(); }

Summary

Lodash provides rich array operation methods covering array creation, filtering, finding, deduplication, sorting, transformation, grouping, slicing, and checking. Mastering these methods can greatly improve the efficiency of array processing and code readability. In actual development, it's recommended to choose appropriate methods based on specific needs and make full use of method chaining to simplify code.

标签:Lodash