DEV Community

Cover image for How to Master Lodash: A Comprehensive Guide
Jinad AbdulQuadri
Jinad AbdulQuadri

Posted on

How to Master Lodash: A Comprehensive Guide

Among the many Javascript libraries, Lodash shines as a powerful utility. Often underestimated, Lodash boasts a wealth of functions designed to streamline everyday programming tasks. Whether you're manipulating arrays or managing objects, Lodash can greatly simplify your code and enhance its readability and quality.

In this guide, I'll furnish you with practical examples and insights to empower you with the skills needed to leverage Lodash's capabilities in your projects.

Step 1: Installation

Before you can start using Lodash, you need to install it in your project. Open your terminal and navigate to your project directory. Then, run the following command to install Lodash as a dependency using npm:

npm install lodash
Enter fullscreen mode Exit fullscreen mode

Step 2: Importing Lodash

Once installed, you can import Lodash into your JavaScript files. You can import the entire Lodash library or specific functions from it. Here's how you can import the entire library:

const _ = require('lodash');
Enter fullscreen mode Exit fullscreen mode

In the above code, we're using _ as an alias for Lodash. This is a common convention to keep your code concise.

Step 3: Using Lodash Functions

Lodash provides a vast range of functions. Let's explore a few examples:

Array Manipulation:

Splitting an array into chunks

You have an array of tasks, and you want to split them into groups of two for better organization. Here’s how you can do that with Lodash:

const tasks = ['Task A', 'Task B', 'Task C', 'Task D', 'Task E'];

// Split the tasks into chunks of two using Lodash
const taskChunks = _.chunk(tasks, 2);

// Output: [['Task A', 'Task B'], ['Task C', 'Task D'], ['Task E']]
Enter fullscreen mode Exit fullscreen mode

Notice the simplicity Lodash brings? Now, contrast it with the verbosity of the non-Lodash code.

const tasks = ['Task A', 'Task B', 'Task C', 'Task D', 'Task E'];

function chunkArray(array, chunkSize) {
    const chunks = [];
    for (let i = 0; i < array.length; i += chunkSize) {
        chunks.push(array.slice(i, i + chunkSize));
    }
    return chunks;
}

const taskChunks = chunkArray(tasks, 2);

// Output: [['Task A', 'Task B'], ['Task C', 'Task D'], ['Task E']]
Enter fullscreen mode Exit fullscreen mode

Let’s check other examples under array manipulation.

Randomly Shuffling an Array

You have a deck of cards represented as an array, and you want to shuffle them randomly.

const deck = ['Ace', 'King', 'Queen', 'Jack', '10', '9', '8', '7'];

//With Lodash
const shuffledDeck = _.shuffle(deck);

// Without Lodash
function shuffleArray(array) {
    const shuffled = [...array];
    for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
}

const shuffledDeck = shuffleArray(deck);

// Output: Randomly shuffled array
Enter fullscreen mode Exit fullscreen mode
Calculating Differences between Arrays

We want to compare two arrays, list and toRemove, to find unique items.

const list = ['A', 'B', 'C', 'D', 'E'];
const toRemove = ['B', 'E', 'F'];


// With Lodash
const uniqueItems = _.xor(list, toRemove);

// Without Lodash
function findUniqueItems(array1, array2) {
    const unique1 = array1.filter(item => !array2.includes(item));
    const unique2 = array2.filter(item => !array1.includes(item));
    return unique1.concat(unique2);
}

const uniqueItems = findUniqueItems(list, toRemove);

// Output: ['A', 'C', 'D', 'F']
Enter fullscreen mode Exit fullscreen mode

Having explored the contrasting efficiency of Lodash versus non-Lodash code, let's delve deeper into various additional use cases where Lodash's capabilities shine brightly.

Object Manipulation:

Deep Merging Objects

You have two objects with nested properties, and you want to merge them deeply.

const object1 = { a: { b: 1 } };
const object2 = { a: { c: 2 } };

// With Lodash
const mergedObject = _.merge({}, object1, object2);

// Without Lodash
const mergedObject = Object.assign({}, object1, { a: Object.assign({}, object1.a, object2.a) });

// Output: { a: { b: 1, c: 2 } }
Enter fullscreen mode Exit fullscreen mode
Picking Specific Properties

You have an object with multiple properties, and you want to create a new object containing only specific properties.

// With Lodash
const originalObject = { name: 'John', age: 30, email: 'john@example.com' };
const pickedProperties = _.pick(originalObject, ['name', 'email']);

// Without Lodash
const pickedProperties = {
    name: originalObject.name,
    email: originalObject.email
};

// Output: { name: 'John', email: 'john@example.com' }
Enter fullscreen mode Exit fullscreen mode
Renaming Object Keys

You have an object with keys in snake_case, and you want to convert them to camelCase.

const originalObject = { first_name: 'John', last_name: 'Doe' };

// With Lodash
const camelCaseObject = _.mapKeys(originalObject, (value, key) => _.camelCase(key));

// Without Lodash
const camelCaseObject = {};
for (const key in originalObject) {
    camelCaseObject[_.camelCase(key)] = originalObject[key];
}

// Output: { firstName: 'John', lastName: 'Doe' }
Enter fullscreen mode Exit fullscreen mode

Functional Programming:

Currying

Currying is the process of converting multi-argument functions into a sequence of single-argument functions.

// With Lodash
const add = _.curry((a, b) => a + b);
const add5 = add(5);
console.log(add5(10)); // Output: 15

// Without Lodash
function add(a) {
    return function(b) {
        return a + b;
    };
}

const add5 = add(5);
console.log(add5(10)); // Output: 15
Enter fullscreen mode Exit fullscreen mode
Memoization

Memoization is a technique where the results of expensive function calls are cached and returned when the same inputs occur again.

// With Lodash
const memoizedFactorial = _.memoize((n) => {
    if (n === 0 || n === 1) {
        return 1;
    }
    return n * memoizedFactorial(n - 1);
});

console.log(memoizedFactorial(5)); // Output: 120 (cached)
console.log(memoizedFactorial(6)); // Output: 720 (cached)

// Without Lodash
const memo = {};
function factorial(n) {
    if (n === 0 || n === 1) {
        return 1;
    }
    if (memo[n]) {
        return memo[n];
    }
    memo[n] = n * factorial(n - 1);
    return memo[n];
}

console.log(factorial(5)); // Output: 120 (cached)
console.log(factorial(6)); // Output: 720 (cached)
Enter fullscreen mode Exit fullscreen mode
Composition

Function composition involves merging two or more functions to create a fresh function.

const greet = (name) => `Hello, ${name}!`;
const toUpperCase = (str) => str.toUpperCase();

// With Lodash
const greetAndUppercase = _.flowRight(greet, toUpperCase);
console.log(greetAndUppercase('John')); // Output: "Hello, JOHN!"

// Without Lodash
const greetAndUppercase = (name) => greet(toUpperCase(name));
console.log(greetAndUppercase('John')); // Output: "Hello, JOHN!"
Enter fullscreen mode Exit fullscreen mode

Step 4: Explore the Documentation

Lodash's documentation is an invaluable resource. It provides detailed information about each function, its usage, and examples. Explore the documentation to discover the full range of functions Lodash offers and find the ones that fit your needs:

Lodash Documentation

Step 5: Use Lodash Responsibly

While Lodash can simplify your code, be mindful of using it appropriately. Importing the entire library can add unnecessary bulk to your project. Instead, import only the functions you need to optimize your codebase's size and performance.

Lodash is a versatile tool that can save you time and improve your code quality. By following these guidelines, you'll be well on your way to leveraging its power effectively in your JavaScript projects.

Top comments (1)

Collapse
 
josephmaina profile image
Joseph Maina

A great introduction to the Lodash library.

Thanks for sharing.