This notebook demonstrates the most useful methods from the Lodash library, a modern JavaScript utility library delivering modularity, performance & extras.
$ npm install lodash up to date in 414ms 28 packages are looking for funding run `npm fund` for details
Lodash version: 4.17.21
Lodash provides numerous methods for working with arrays.
Creates an array of elements split into groups of the specified size.
Chunked array:[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
Creates an array with all falsey values removed. Falsey values are false
, null
, 0
, ""
, undefined
, and NaN
.
Compact array (falsey values removed):[ 1, 2, 3 ]
Creates a new array concatenating array with additional values.
Concatenated array:[ 1, 2, 3, [ 4 ] ]
Creates an array of values not included in the other provided arrays.
Difference between arrays:[ 1, 5 ]
flatten
: Flattens array a single level deepflattenDeep
: Recursively flattens arrayFlattened array (one level):[ 1, 2, [ 3, [ 4 ] ], 5 ] Deeply flattened array (all levels):[ 1, 2, 3, 4, 5 ]
Creates an array of unique values that are included in all given arrays.
Intersection of arrays:[ 2, 3 ]
Removes all given values from array. Note: This method mutates the original array.
Original array: [ 'a', 'b', 'c', 'a', 'b', 'c' ] After pulling 'a' and 'c':[ 'b', 'b' ]
Creates a duplicate-free version of an array.
Array with duplicates removed:[ 2, 1, 3, 4 ]
These methods work on both arrays and objects.
Creates an object composed of keys generated from the results of running each element of collection through iteratee.
Count by Math.floor:{ '4': 1, '6': 2 } Count by string length:{ '3': 2, '5': 1 }
Creates an object composed of keys generated from the results of running each element of collection through iteratee.
Grouped by string length:{ '3': [ 'one', 'two' ], '4': [ 'four', 'five' ], '5': [ 'three' ] }
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
Even numbers:[ 2, 4, 6 ] Active users:[ { user: 'barney', age: 36, active: true } ]
Iterates over elements of collection, returning the first element predicate returns truthy for.
First number greater than 2:3 User with age 1 and active status true:{ user: 'pebbles', age: 1, active: true }
Creates an array of values by running each element in collection through iteratee.
Squares:[ 1, 4, 9, 16 ] User names:[ 'barney', 'fred' ]
Reduces collection to a value which is the accumulated result of running each element in collection through iteratee.
Sum of array:10 Object built from array:{ a: 1, b: 2, c: 3 }
sample
: Gets a random element from collectionsampleSize
: Gets n random elements from collectionRandom element:3 3 random elements:[ 2, 1, 5 ]
Lodash provides powerful utilities for working with objects.
Assigns own enumerable string keyed properties of source objects to the destination object.
Assigned object:{ a: 1, b: 2, c: 3 } Original object (modified):{ a: 1, b: 2, c: 3 }
Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned.
Value at a[0].b.c:3 Value at ['a', '0', 'b', 'c']:3 Value at non-existent path a.b.c (with default):default
Checks if path is a direct property of object.
Has path 'a.b': trueHas path ['a', 'b']: trueHas path 'a.c': false
Recursively merges own and inherited enumerable string keyed properties of source objects into the destination object.
Merged object:{ "a": [ { "b": 2, "c": 3 }, { "d": 4, "e": 5 } ] }
omit
: Creates an object excluding the given propertiespick
: Creates an object composed of the picked object propertiesObject with 'a' and 'c' omitted:{ b: 2, d: 4 } Object with only 'a' and 'c' picked:{ a: 1, c: 3 }
Lodash provides utilities for string manipulation.
Lodash provides several methods for converting strings to different cases.
Original: Lodash String MethodscamelCase: lodashStringMethodskebabCase: lodash-string-methodssnakeCase: lodash_string_methodsstartCase: Lodash String Methodscapitalize: Lodash string methods
escape
: Converts characters to HTML entitiesunescape
: Converts HTML entities to charactersOriginal HTML: <p>Hello & welcome</p>Escaped HTML: <p>Hello & welcome</p>Unescaped HTML: <p>Hello & welcome</p>
Truncates string if it's longer than the given maximum string length.
Truncated to 24 chars:This is a very long s... Custom truncation:This is a very... (read more)
Lodash provides utilities for working with functions.
Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
Calling debounced function multiple times...Only the last call will be executed after 1000ms
Creates a throttled function that only invokes func at most once per every wait milliseconds.
Calling throttled function multiple times...Throttled function called with: first callOnly the first call executes immediately, others are throttled
Lodash provides various utility functions.
Invokes the iteratee n times, returning an array of the results.
Result of _.times(5, String):[ '0', '1', '2', '3', '4' ] Generate array of user objects:[ { id: 0, name: 'User 0' }, { id: 1, name: 'User 1' }, { id: 2, name: 'User 2' } ]
Produces a random number between min and max (inclusive).
Random integer between 0 and 5:2 Random integer between 0 and 5 (shorthand):4 Random float between 1.2 and 5.2:3.3401687410575533 Random float between 0 and 5:4.685684836099512
Generates a unique ID.
Unique ID without prefix: 1Unique ID without prefix: 2 Unique ID with prefix: user_3Unique ID with prefix: user_4
Lodash provides a powerful chaining mechanism to perform multiple operations in sequence.
Result of chained operations:[ 'pebbles is 1', 'wilma is 35', 'barney is 36' ]
Let's explore some practical applications of Lodash in real-world scenarios.
Processed student data:[ { id: 2, name: 'Jane', averageScore: 92, passed: true }, { id: 4, name: 'Alice', averageScore: 87.33333333333333, passed: true }, { id: 1, name: 'John', averageScore: 84.33333333333333, passed: true } ]
All teams (flattened):[ { name: 'Frontend', members: 8, location: 'Floor 2' }, { name: 'Backend', members: 12, location: 'Floor 1' }, { name: 'DevOps', members: 5, location: 'Floor 1' }, { name: 'Digital', members: 6, location: 'Floor 3' }, { name: 'Events', members: 4, location: 'Floor 3' }, { name: 'Domestic', members: 10, location: 'Floor 4' }, { name: 'International', members: 15, location: 'Floor 4' } ] Teams grouped by location:{ 'Floor 2': [ { name: 'Frontend', members: 8, location: 'Floor 2' } ], 'Floor 1': [ { name: 'Backend', members: 12, location: 'Floor 1' }, { name: 'DevOps', members: 5, location: 'Floor 1' } ], 'Floor 3': [ { name: 'Digital', members: 6, location: 'Floor 3' }, { name: 'Events', members: 4, location: 'Floor 3' } ], 'Floor 4': [ { name: 'Domestic', members: 10, location: 'Floor 4' }, { name: 'International', members: 15, location: 'Floor 4' } ] } Member count by department:[ { department: 'Engineering', totalMembers: 25, teamCount: 3 }, { department: 'Marketing', totalMembers: 10, teamCount: 2 }, { department: 'Sales', totalMembers: 25, teamCount: 2 } ]
Expenses analysis by category:{ Food: { count: 3, total: 89.45, average: 29.816666666666666, min: 25.5, max: 35.2 }, Transport: { count: 2, total: 36.05, average: 18.025, min: 15.75, max: 20.3 }, Entertainment: { count: 1, total: 45.8, average: 45.8, min: 45.8, max: 45.8 }, Utilities: { count: 1, total: 85.5, average: 85.5, min: 85.5, max: 85.5 } } Top spending categories:[ { category: 'Food', total: 89.45 }, { category: 'Utilities', total: 85.5 } ]
Processed form data:{ firstName: 'John', lastName: 'Doe', email: 'john.doe@example.com', age: 32, interests: [ 'programming', 'music', 'hiking' ], address: { street: '123 Main St', city: 'Anytown', zipCode: '12345' }, subscribeToNewsletter: true, fullName: 'John Doe' }
Available products count: 4 Computer products:[ 'Laptop', 'Monitor', 'Keyboard' ] Total inventory value: $53548.85 Most expensive product: Laptop ($999.99) Products by category:{ electronics: [ 'Laptop', 'Smartphone', 'Headphones', 'Monitor', 'Keyboard' ], computers: [ 'Laptop', 'Monitor', 'Keyboard' ], phones: [ 'Smartphone' ], audio: [ 'Headphones' ] }
This notebook has demonstrated many of Lodash's powerful utility functions for working with arrays, objects, collections, strings, and more. Lodash makes JavaScript data manipulation much more concise and readable, especially when dealing with complex data structures.
Key benefits of using Lodash include:
While modern JavaScript has incorporated many features that were once unique to Lodash (like Array.map
, Array.filter
, etc.), Lodash still provides significant value through its comprehensive API, consistent behavior, and powerful utilities for complex data manipulation.