Logo
⚠️ Unsaved
[M]:

Lodash Methods Showcase

This notebook demonstrates the most useful methods from the Lodash library, a modern JavaScript utility library delivering modularity, performance & extras.

[1]:
// Install Lodash
!npm install lodash
$ npm install lodash

added 1 package in 2s

28 packages are looking for funding
  run `npm fund` for details
[3]:
// Import Lodash
import * as _ from 'lodash';

// Display Lodash version
console.log("Lodash version:", _.VERSION);
Lodash version: 4.17.21
[M]:

Array Methods

Lodash provides numerous methods for working with arrays.

[M]:

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

Creates an array of elements split into groups of the specified size.

[4]:
// Split array into chunks of size 2
const chunkedArray = _.chunk([1, 2, 3, 4, 5], 2);

console.log("Chunked array:");
console.log(chunkedArray);
Chunked array:[ [ 1, 2, 3 ], [ 4, 5 ] ]
[M]:

_.compact(array)

Creates an array with all falsey values removed. Falsey values are false, null, 0, "", undefined, and NaN.

[8]:
// Remove all falsey values
const compactArray = _.compact([0, 1, false, 2, '', 3, null, undefined, NaN]);

console.log("Compact array (falsey values removed):");
console.log(compactArray);
Compact array (falsey values removed):[ 1, 2, 3 ]
[M]:

_.concat(array, [values])

Creates a new array concatenating array with additional values.

[9]:
// Concatenate arrays and values
const concatArray = _.concat([1], 2, [3], [[4]]);

console.log("Concatenated array:");
console.log(concatArray);
Concatenated array:[ 1, 2, 3, [ 4 ] ]
[M]:

_.difference(array, [values])

Creates an array of values not included in the other provided arrays.

[10]:
// Find values in first array that aren't in second array
const diffArray = _.difference([2, 1, 5], [2, 3]);

console.log("Difference between arrays:");
console.log(diffArray);
Difference between arrays:[ 1, 5 ]
[M]:

_.flatten(array) and _.flattenDeep(array)

  • flatten: Flattens array a single level deep
  • flattenDeep: Recursively flattens array
[11]:
const nestedArray = [1, [2, [3, [4]], 5]];

// Flatten one level
const flattenedArray = _.flatten(nestedArray);
console.log("Flattened array (one level):");
console.log(flattenedArray);

// Flatten all levels
const deeplyFlattenedArray = _.flattenDeep(nestedArray);
console.log("\nDeeply flattened array (all levels):");
console.log(deeplyFlattenedArray);
Flattened array (one level):[ 1, 2, [ 3, [ 4 ] ], 5 ]
Deeply flattened array (all levels):[ 1, 2, 3, 4, 5 ]
[M]:

_.intersection([arrays])

Creates an array of unique values that are included in all given arrays.

[12]:
// Find values common to all arrays
const intersectionArray = _.intersection([2, 1, 3], [2, 3, 4], [2, 5, 3]);

console.log("Intersection of arrays:");
console.log(intersectionArray);
Intersection of arrays:[ 2, 3 ]
[M]:

_.pull(array, [values])

Removes all given values from array. Note: This method mutates the original array.

[13]:
// Remove specific values from array
const array = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log("Original array:", array);

_.pull(array, 'a', 'c');
console.log("\nAfter pulling 'a' and 'c':");
console.log(array);
Original array: [ 'a', 'b', 'c', 'a', 'b', 'c' ]
After pulling 'a' and 'c':[ 'b', 'b' ]
[M]:

_.uniq(array)

Creates a duplicate-free version of an array.

[14]:
// Remove duplicates from array
const uniqueArray = _.uniq([2, 1, 2, 3, 1, 4]);

console.log("Array with duplicates removed:");
console.log(uniqueArray);
Array with duplicates removed:[ 2, 1, 3, 4 ]
[M]:

Collection Methods

These methods work on both arrays and objects.

[M]:

.countBy(collection, [iteratee=.identity])

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

[15]:
// Count occurrences by the result of the iteratee function
const countByFloor = _.countBy([6.1, 4.2, 6.3], Math.floor);
console.log("Count by Math.floor:");
console.log(countByFloor);

// Count by property
const countByLength = _.countBy(['one', 'two', 'three'], 'length');
console.log("\nCount by string length:");
console.log(countByLength);
Count by Math.floor:{ '4': 1, '6': 2 }
Count by string length:{ '3': 2, '5': 1 }
[M]:

.groupBy(collection, [iteratee=.identity])

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

[16]:
// Group by string length
const groupedByLength = _.groupBy(['one', 'two', 'three', 'four', 'five'], 'length');

console.log("Grouped by string length:");
console.log(groupedByLength);
Grouped by string length:{ '3': [ 'one', 'two' ], '4': [ 'four', 'five' ], '5': [ 'three' ] }
[M]:

.filter(collection, [predicate=.identity])

Iterates over elements of collection, returning an array of all elements predicate returns truthy for.

[17]:
// Filter even numbers
const evens = _.filter([1, 2, 3, 4, 5, 6], n => n % 2 === 0);
console.log("Even numbers:");
console.log(evens);

// Filter by property
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];

const activeUsers = _.filter(users, { 'active': true });
console.log("\nActive users:");
console.log(activeUsers);
Even numbers:[ 2, 4, 6 ]
Active users:[ { user: 'barney', age: 36, active: true } ]
[M]:

.find(collection, [predicate=.identity], [fromIndex=0])

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

[18]:
// Find first number greater than 2
const firstGreaterThanTwo = _.find([1, 2, 3, 4], n => n > 2);
console.log("First number greater than 2:");
console.log(firstGreaterThanTwo);

// Find by object properties
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
];

const user = _.find(users, { 'age': 1, 'active': true });
console.log("\nUser with age 1 and active status true:");
console.log(user);
First number greater than 2:3
User with age 1 and active status true:{ user: 'pebbles', age: 1, active: true }
[M]:

.map(collection, [iteratee=.identity])

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

[19]:
// Map numbers to their squares
const squares = _.map([1, 2, 3, 4], n => n * n);
console.log("Squares:");
console.log(squares);

// Map objects to a specific property
const users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];

const names = _.map(users, 'user');
console.log("\nUser names:");
console.log(names);
Squares:[ 1, 4, 9, 16 ]
User names:[ 'barney', 'fred' ]
[M]:

.reduce(collection, [iteratee=.identity], [accumulator])

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

[20]:
// Sum all numbers in array
const sum = _.reduce([1, 2, 3, 4], (total, n) => total + n, 0);
console.log("Sum of array:");
console.log(sum);

// Build an object from array
const array = [['a', 1], ['b', 2], ['c', 3]];
const object = _.reduce(array, (result, [key, value]) => {
result[key] = value;
return result;
}, {});

console.log("\nObject built from array:");
console.log(object);
Sum of array:10
Object built from array:{ a: 1, b: 2, c: 3 }
[M]:

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

  • sample: Gets a random element from collection
  • sampleSize: Gets n random elements from collection
[21]:
// Get a random element
const randomElement = _.sample([1, 2, 3, 4, 5]);
console.log("Random element:");
console.log(randomElement);

// Get 3 random elements
const randomElements = _.sampleSize([1, 2, 3, 4, 5], 3);
console.log("\n3 random elements:");
console.log(randomElements);
Random element:3
3 random elements:[ 2, 1, 5 ]
[M]:

Object Methods

Lodash provides powerful utilities for working with objects.

[M]:

_.assign(object, [sources])

Assigns own enumerable string keyed properties of source objects to the destination object.

[22]:
// Merge objects together
const destination = { 'a': 1 };
const source1 = { 'b': 2 };
const source2 = { 'c': 3 };

const result = _.assign(destination, source1, source2);

console.log("Assigned object:");
console.log(result);
console.log("\nOriginal object (modified):");
console.log(destination);
Assigned object:{ a: 1, b: 2, c: 3 }
Original object (modified):{ a: 1, b: 2, c: 3 }
[M]:

_.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned.

[23]:
// Access nested properties safely
const object = { 'a': [{ 'b': { 'c': 3 } }] };

// Using dot notation
const value1 = _.get(object, 'a[0].b.c');
console.log("Value at a[0].b.c:");
console.log(value1);

// Using array notation
const value2 = _.get(object, ['a', '0', 'b', 'c']);
console.log("\nValue at ['a', '0', 'b', 'c']:");
console.log(value2);

// With default value for non-existent path
const value3 = _.get(object, 'a.b.c', 'default');
console.log("\nValue at non-existent path a.b.c (with default):");
console.log(value3);
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
[M]:

_.has(object, path)

Checks if path is a direct property of object.

[24]:
// Check if path exists in object
const object = { 'a': { 'b': 2 } };

const hasPath1 = _.has(object, 'a.b');
console.log("Has path 'a.b':", hasPath1);

const hasPath2 = _.has(object, ['a', 'b']);
console.log("Has path ['a', 'b']:", hasPath2);

const hasPath3 = _.has(object, 'a.c');
console.log("Has path 'a.c':", hasPath3);
Has path 'a.b': trueHas path ['a', 'b']: trueHas path 'a.c': false
[M]:

_.merge(object, [sources])

Recursively merges own and inherited enumerable string keyed properties of source objects into the destination object.

[25]:
// Deep merge objects
const object1 = {
'a': [{ 'b': 2 }, { 'd': 4 }]
};

const object2 = {
'a': [{ 'c': 3 }, { 'e': 5 }]
};

const merged = _.merge(object1, object2);

console.log("Merged object:");
console.log(JSON.stringify(merged, null, 2));
Merged object:{
  "a": [
    {
      "b": 2,
      "c": 3
    },
    {
      "d": 4,
      "e": 5
    }
  ]
}
[M]:

_.omit(object, [paths]) and _.pick(object, [paths])

  • omit: Creates an object excluding the given properties
  • pick: Creates an object composed of the picked object properties
[26]:
const object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 };

// Omit specific properties
const omitted = _.omit(object, ['a', 'c']);
console.log("Object with 'a' and 'c' omitted:");
console.log(omitted);

// Pick specific properties
const picked = _.pick(object, ['a', 'c']);
console.log("\nObject with only 'a' and 'c' picked:");
console.log(picked);
Object with 'a' and 'c' omitted:{ b: 2, d: 4 }
Object with only 'a' and 'c' picked:{ a: 1, c: 3 }
[M]:

String Methods

Lodash provides utilities for string manipulation.

[M]:

String Case Conversion

Lodash provides several methods for converting strings to different cases.

[27]:
const text = "Lodash String Methods";

console.log("Original:", text);
console.log("camelCase:", _.camelCase(text));
console.log("kebabCase:", _.kebabCase(text));
console.log("snakeCase:", _.snakeCase(text));
console.log("startCase:", _.startCase(text));
console.log("capitalize:", _.capitalize(text.toLowerCase()));
Original: Lodash String MethodscamelCase: lodashStringMethodskebabCase: lodash-string-methodssnakeCase: lodash_string_methodsstartCase: Lodash String Methodscapitalize: Lodash string methods
[M]:

_.escape(string) and _.unescape(string)

  • escape: Converts characters to HTML entities
  • unescape: Converts HTML entities to characters
[28]:
const html = "<p>Hello & welcome</p>";

// Escape HTML
const escaped = _.escape(html);
console.log("Original HTML:", html);
console.log("Escaped HTML:", escaped);

// Unescape HTML
const unescaped = _.unescape(escaped);
console.log("Unescaped HTML:", unescaped);
Original HTML: <p>Hello & welcome</p>Escaped HTML: &lt;p&gt;Hello &amp; welcome&lt;/p&gt;Unescaped HTML: <p>Hello & welcome</p>
[M]:

_.truncate(string, [options={}])

Truncates string if it's longer than the given maximum string length.

[29]:
const longText = "This is a very long string that needs to be truncated for display purposes.";

// Basic truncation
const truncated1 = _.truncate(longText, { 'length': 24 });
console.log("Truncated to 24 chars:");
console.log(truncated1);

// Custom separator and omission
const truncated2 = _.truncate(longText, {
'length': 30,
'separator': ' ',
'omission': '... (read more)'
});
console.log("\nCustom truncation:");
console.log(truncated2);
Truncated to 24 chars:This is a very long s...
Custom truncation:This is a very... (read more)
[M]:

Function Methods

Lodash provides utilities for working with functions.

[M]:

_.debounce(func, [wait=0], [options={}])

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.

[30]:
// Create a debounced function
const debounced = _.debounce(function(text) {
console.log(`Debounced function called with: ${text}`);
}, 1000);

// In a real application, this would be called multiple times
// but only execute once after 1000ms of inactivity
console.log("Calling debounced function multiple times...");
debounced("first call");
debounced("second call");
debounced("third call");
console.log("Only the last call will be executed after 1000ms");
Calling debounced function multiple times...Only the last call will be executed after 1000ms
[M]:

_.throttle(func, [wait=0], [options={}])

Creates a throttled function that only invokes func at most once per every wait milliseconds.

[31]:
// Create a throttled function
const throttled = _.throttle(function(text) {
console.log(`Throttled function called with: ${text}\n`);
}, 1000);

// In a real application, this might be called many times
// but would only execute once every 1000ms
console.log("Calling throttled function multiple times...");
throttled("first call");
throttled("second call"); // ignored until 1000ms passes
throttled("third call"); // ignored until 1000ms passes
console.log("Only the first call executes immediately, others are throttled");
Calling throttled function multiple times...Throttled function called with: first callOnly the first call executes immediately, others are throttled
[M]:

Utility Methods

Lodash provides various utility functions.

[M]:

.times(n, [iteratee=.identity])

Invokes the iteratee n times, returning an array of the results.

[32]:
// Execute a function multiple times
const result1 = _.times(5, String);
console.log("Result of _.times(5, String):");
console.log(result1);

// Generate an array of objects
const result2 = _.times(3, (index) => ({ id: index, name: `User ${index}` }));
console.log("\nGenerate array of user objects:");
console.log(result2);
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' }
]
[M]:

_.random([lower=0], [upper=1], [floating])

Produces a random number between min and max (inclusive).

[33]:
// Random integer between 0 and 5
console.log("Random integer between 0 and 5:");
console.log(_.random(0, 5));

// Random integer between 0 and 5
console.log("\nRandom integer between 0 and 5 (shorthand):");
console.log(_.random(5));

// Random floating point number between 1.2 and 5.2
console.log("\nRandom float between 1.2 and 5.2:");
console.log(_.random(1.2, 5.2));

// Force floating point result
console.log("\nRandom float between 0 and 5:");
console.log(_.random(0, 5, true));
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
[M]:

_.uniqueId([prefix=''])

Generates a unique ID.

[34]:
// Generate unique IDs
console.log("Unique ID without prefix:", _.uniqueId());
console.log("Unique ID without prefix:", _.uniqueId());
console.log("\nUnique ID with prefix:", _.uniqueId('user_'));
console.log("Unique ID with prefix:", _.uniqueId('user_'));
Unique ID without prefix: 1Unique ID without prefix: 2
Unique ID with prefix: user_3Unique ID with prefix: user_4
[M]:

Method Chaining

Lodash provides a powerful chaining mechanism to perform multiple operations in sequence.

[35]:
// Sample data
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true },
{ 'user': 'wilma', 'age': 35, 'active': true }
];

// Chain multiple operations
const result = _
.chain(users)
.filter('active') // Get active users
.sortBy('age') // Sort by age
.map(user => { // Format user data
return `${user.user} is ${user.age}`;
})
.value(); // Execute the chain

console.log("Result of chained operations:");
console.log(result);
Result of chained operations:[ 'pebbles is 1', 'wilma is 35', 'barney is 36' ]
[M]:

Real-world Examples

Let's explore some practical applications of Lodash in real-world scenarios.

[M]:

Example 1: Data Transformation

[36]:
// Raw student data
const students = [
{ id: 1, name: 'John', scores: [85, 90, 78] },
{ id: 2, name: 'Jane', scores: [92, 95, 89] },
{ id: 3, name: 'Bob', scores: [70, 65, 72] },
{ id: 4, name: 'Alice', scores: [88, 84, 90] }
];

// Process student data
const processedStudents = _.chain(students)
.map(student => ({
id: student.id,
name: student.name,
averageScore: _.mean(student.scores),
passed: _.mean(student.scores) >= 75
}))
.filter('passed') // Only include passing students
.sortBy('averageScore') // Sort by average score
.reverse() // Highest scores first
.value();

console.log("Processed student data:");
console.log(processedStudents);
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
  }
]
[M]:

Example 2: Working with Nested Data

[37]:
// Nested company data
const company = {
departments: [
{
name: 'Engineering',
teams: [
{ name: 'Frontend', members: 8, location: 'Floor 2' },
{ name: 'Backend', members: 12, location: 'Floor 1' },
{ name: 'DevOps', members: 5, location: 'Floor 1' }
]
},
{
name: 'Marketing',
teams: [
{ name: 'Digital', members: 6, location: 'Floor 3' },
{ name: 'Events', members: 4, location: 'Floor 3' }
]
},
{
name: 'Sales',
teams: [
{ name: 'Domestic', members: 10, location: 'Floor 4' },
{ name: 'International', members: 15, location: 'Floor 4' }
]
}
]
};

// Extract all teams
const allTeams = _.flatMap(company.departments, 'teams');
console.log("All teams (flattened):");
console.log(allTeams);

// Group teams by location
const teamsByLocation = _.groupBy(allTeams, 'location');
console.log("\nTeams grouped by location:");
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 }
]
[M]:

Example 3: Data Analysis and Aggregation

[38]:
// Transaction data
const transactions = [
{ id: 1, date: '2023-01-15', category: 'Food', amount: 25.50, status: 'completed' },
{ id: 2, date: '2023-01-16', category: 'Transport', amount: 15.75, status: 'completed' },
{ id: 3, date: '2023-01-20', category: 'Food', amount: 35.20, status: 'completed' },
{ id: 4, date: '2023-01-25', category: 'Utilities', amount: 100.00, status: 'pending' },
{ id: 5, date: '2023-01-27', category: 'Transport', amount: 20.30, status: 'completed' },
{ id: 6, date: '2023-01-30', category: 'Entertainment', amount: 45.80, status: 'completed' },
{ id: 7, date: '2023-02-02', category: 'Food', amount: 28.75, status: 'completed' },
{ id: 8, date: '2023-02-05', category: 'Utilities', amount: 85.50, status: 'completed' },
{ id: 9, date: '2023-02-10', category: 'Entertainment', amount: 65.25, status: 'pending' }
];

// Filter completed transactions
const completedTransactions = _.filter(transactions, { status: 'completed' });

// Group by category and calculate statistics
const expensesByCategory = _.chain(completedTransactions)
.groupBy('category')
.mapValues(items => ({
count: items.length,
total: _.sumBy(items, 'amount'),
average: _.meanBy(items, 'amount'),
min: _.minBy(items, 'amount').amount,
max: _.maxBy(items, 'amount').amount
}))
.value();

console.log("Expenses analysis by category:");
console.log(expensesByCategory);

// Find top spending categories
const topCategories = _.chain(expensesByCategory)
.map((stats, category) => ({
category,
total: stats.total
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 }
]
[M]:

Example 4: Form Data Processing

[39]:
// Simulated form submission data
const formData = {
firstName: ' John ',
lastName: 'Doe',
email: 'john.doe@example.com',
age: '32',
interests: ['programming', 'music', 'hiking'],
address: {
street: '123 Main St',
city: 'Anytown',
zipCode: '12345'
},
newsletter: 'yes',
comments: '',
referrer: null
};

// Clean and process form data
const processedForm = _.chain(formData)
// Remove empty fields
.omitBy(value => _.isNull(value) || value === '')
// Process specific fields
.assign({
// Trim whitespace from strings
firstName: _.trim(formData.firstName),
// Convert string to number
age: parseInt(formData.age, 10),
// Convert yes/no to boolean
subscribeToNewsletter: formData.newsletter === 'yes',
// Create full name
fullName: `${_.trim(formData.firstName)} ${formData.lastName}`
})
// Remove original newsletter field
.omit(['newsletter'])
.value();

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'
}
[M]:

Example 5: Working with API Responses

[40]:
// Simulated API response
const apiResponse = {
status: "success",
data: {
products: [
{ id: "p1", name: "Laptop", price: 999.99, stock: 45, categories: ["electronics", "computers"] },
{ id: "p2", name: "Smartphone", price: 699.99, stock: 0, categories: ["electronics", "phones"] },
{ id: "p3", name: "Headphones", price: 149.99, stock: 23, categories: ["electronics", "audio"] },
{ id: "p4", name: "Monitor", price: 249.99, stock: 12, categories: ["electronics", "computers"] },
{ id: "p5", name: "Keyboard", price: 59.99, stock: 35, categories: ["electronics", "computers"] }
],
pagination: {
currentPage: 1,
totalPages: 3,
itemsPerPage: 5
}
}
};

// Process API response
if (apiResponse.status === "success") {
// Extract products
const products = apiResponse.data.products;
// Get available products
const availableProducts = _.filter(products, product => product.stock > 0);
console.log("Available products count:", availableProducts.length);
// Get computer products
const computerProducts = _.filter(products, product =>
_.includes(product.categories, "computers")
);
console.log("\nComputer products:");
console.log(_.map(computerProducts, 'name'));
// Calculate total inventory value
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' ]
}
[M]:

Conclusion

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:

  1. Consistency: Provides consistent behavior across browsers and environments
  2. Performance: Optimized implementations of common operations
  3. Readability: Makes code more expressive and easier to understand
  4. Chaining: Allows for elegant composition of multiple operations
  5. Edge Cases: Handles many edge cases that might be overlooked in custom implementations

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.

Sign in to save your work and access it from anywhere