Skip to footer content
NODE HELP

Lodash NPM (How It Works For Developers)

Lodash is a modern JavaScript utility library delivering modularity, performance, and extras. It helps developers write more concise and maintainable code by providing a wide range of utility functions for common programming tasks.

In this article, we'll dive deep into Lodash, exploring its features, benefits, and how to use it effectively in your JS projects.

What is Lodash?

Lodash is a JavaScript library that offers utility methods for common programming tasks, such as manipulating arrays, objects, and strings. It was created by John-David Dalton in 2012 as a fork of Underscore.js, another utility library, with the goal of providing better performance and additional features.

Lodash NPM (How It Works For Developers): Figure 1 - Lodash core build

Lodash's modular methods support modern environments, offering composite functions in various module formats. Its core build and FP build enhance JavaScript ease, making string manipulation and iterating arrays simpler. The library, exported in diverse module formats, caters to different needs, with var object and var array handling efficiently. That's why Lodash remains a top choice in the JS libraries landscape.

Key Features of Lodash

Lodash supports modern environments and includes a wide variety of utility functions that can be categorized into several groups:

  1. Array Manipulation: Functions to work with arrays, such as map, filter, reduce, flatten, and uniq.
  2. Object Manipulation: Functions for objects, including assign, keys, values, merge, and omit.
  3. String Manipulation: Functions for string operations like camelCase, capitalize, trim, and escape.
  4. Collection Manipulation: Functions for handling collections (arrays or objects), such as each, groupBy, sortBy, and shuffle.
  5. Function Utilities: Functions to work with functions, including debounce, throttle, curry, and bind.
  6. Math Utilities: Math-related functions like random, clamp, and sum.

Benefits of Using Lodash

1. Simplified Code

Lodash makes JavaScript easier by providing concise and readable methods for common tasks, reducing the amount of code you need to write and maintain.

2. Improved Performance

Lodash composite functions module formats are optimized for performance, often outperforming native JavaScript implementations. This makes it a valuable tool for handling large datasets or performing complex operations.

3. Consistency Across Browsers

JavaScript behavior can vary across different browsers and environments. Lodash provides consistent behavior, helping to avoid cross-browser compatibility issues.

4. Modular Approach

Lodash can be imported as a whole or in smaller, modular parts. This flexibility allows developers to use only those method categories they need, reducing the overall bundle size for their applications.

How to Use Lodash

Installation

Lodash can be installed via npm (Node Package Manager) or yarn:

npm install lodash
npm install lodash
SHELL

Importing Lodash

You can import Lodash into your project using CommonJS or ES6 module syntax. Here's how to do it:

Using CommonJS

const _ = require('lodash');
const _ = require('lodash');
JAVASCRIPT

Using ES6 Modules

import _ from 'lodash';
import _ from 'lodash';
JAVASCRIPT

Basic Usage

Let's explore some common use cases and how Lodash simplifies these tasks.

Array Manipulation

  1. Filtering an Array:

    Use _.filter to create a new array with elements that pass the test implemented by the provided function.

const users = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Jim', age: 35 }
];
const youngUsers = _.filter(users, user => user.age < 30);
console.log(youngUsers); // [{ name: 'John', age: 25 }]
const users = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Jim', age: 35 }
];
const youngUsers = _.filter(users, user => user.age < 30);
console.log(youngUsers); // [{ name: 'John', age: 25 }]
JAVASCRIPT
  1. Finding a Unique Array:

    Use _.uniq to create a duplicate-free version of an array.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = _.uniq(numbers);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = _.uniq(numbers);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
JAVASCRIPT

Object Manipulation

  1. Merging Objects:

    Use _.merge to merge source objects into the destination object by recursively merging their properties.

const object1 = { a: 1, b: 2 };
const object2 = { b: 3, c: 4 };
const mergedObject = _.merge(object1, object2);
console.log(mergedObject); // { a: 1, b: 3, c: 4 }
const object1 = { a: 1, b: 2 };
const object2 = { b: 3, c: 4 };
const mergedObject = _.merge(object1, object2);
console.log(mergedObject); // { a: 1, b: 3, c: 4 }
JAVASCRIPT
  1. Omitting Properties:

    Use _.omit to create an object composed of the object properties that are not omitted.

const object = { a: 1, b: 2, c: 3 };
const newObject = _.omit(object, ['b']);
console.log(newObject); // { a: 1, c: 3 }
const object = { a: 1, b: 2, c: 3 };
const newObject = _.omit(object, ['b']);
console.log(newObject); // { a: 1, c: 3 }
JAVASCRIPT

Function Utilities

  1. Debouncing a Function:

    Use _.debounce to limit a function from being called frequently. This ensures that the function is executed only once in a given time period, regardless of how many times the event it's bound to fires.

const saveInput = _.debounce(() => {
  console.log('Input saved');
}, 300);
// This will only be executed once every 300 milliseconds, regardless of how many times it's called.
const saveInput = _.debounce(() => {
  console.log('Input saved');
}, 300);
// This will only be executed once every 300 milliseconds, regardless of how many times it's called.
JAVASCRIPT
  1. Throttling a Function:

    Use _.throttle to limit a function's execution to no more than once per specified interval.

const updatePosition = _.throttle(() => {
  console.log('Position updated');
}, 1000);
// This function will be executed at most once every second.
const updatePosition = _.throttle(() => {
  console.log('Position updated');
}, 1000);
// This function will be executed at most once every second.
JAVASCRIPT

Using Lodash with IronPDF to Generate PDFs from Data in Node.js

Lodash is a versatile JavaScript utility library that can simplify many data manipulation tasks, while IronPDF for Node.js is a powerful tool for creating and manipulating PDF documents. By combining these two tools, developers can efficiently generate PDFs from various data sources, making it easy to create dynamic reports, invoices, and other documents.

IronPDF for Node.js

IronPDF Overview allows developers to create, edit, and extract content from PDFs. It supports generating PDFs from URLs, HTML files, and HTML strings, providing a flexible approach to PDF creation.

Lodash NPM (How It Works For Developers): Figure 2 - IronPDF

For more detailed information, please visit the IronPDF Documentation for in-depth guidance on using IronPDF functionalities.

Generating a PDF Report from Data

Imagine you have a list of user data, and you need to generate a PDF report that includes each user's information formatted as HTML. Lodash can be used to manipulate and format the data, while IronPDF will handle the PDF creation.

Step-by-Step Guide

  1. Install the Necessary Packages: First, ensure you have both Lodash and IronPDF installed in your Node.js project:
npm i @ironsoftware/ironpdf lodash
npm i @ironsoftware/ironpdf lodash
SHELL
  1. Prepare Your Data: Suppose you have the following user data:
const _ = require('lodash');
const users = [
    { name: 'John Doe', age: 28, email: 'john@example.com' },
    { name: 'Jane Smith', age: 34, email: 'jane@example.com' },
    { name: 'Jim Brown', age: 45, email: 'jim@example.com' }
];
const _ = require('lodash');
const users = [
    { name: 'John Doe', age: 28, email: 'john@example.com' },
    { name: 'Jane Smith', age: 34, email: 'jane@example.com' },
    { name: 'Jim Brown', age: 45, email: 'jim@example.com' }
];
JAVASCRIPT
  1. Format Data with Lodash: Use Lodash to format the user data into an HTML string:
const formatUserData = (users) => {
    return _.map(users, user => {
        return `
            <div>
                <h2>${_.escape(user.name)}</h2>
                <p>Age: ${user.age}</p>
                <p>Email: ${_.escape(user.email)}</p>
            </div>
        `;
    }).join('');
};

const userHtml = `
    <html>
    <head><title>User Report</title></head>
    <body>
        ${formatUserData(users)}
    </body>
    </html>
`;
const formatUserData = (users) => {
    return _.map(users, user => {
        return `
            <div>
                <h2>${_.escape(user.name)}</h2>
                <p>Age: ${user.age}</p>
                <p>Email: ${_.escape(user.email)}</p>
            </div>
        `;
    }).join('');
};

const userHtml = `
    <html>
    <head><title>User Report</title></head>
    <body>
        ${formatUserData(users)}
    </body>
    </html>
`;
JAVASCRIPT
  1. Generate PDF with IronPDF: Use IronPDF to generate a PDF with HTML from the formatted HTML string:
const { PdfDocument } = require('@ironsoftware/ironpdf');
(async () => {
    const pdfFromHtmlString = await PdfDocument.fromHtml(userHtml);
    await pdfFromHtmlString.saveAs("user_report.pdf");
})();
const { PdfDocument } = require('@ironsoftware/ironpdf');
(async () => {
    const pdfFromHtmlString = await PdfDocument.fromHtml(userHtml);
    await pdfFromHtmlString.saveAs("user_report.pdf");
})();
JAVASCRIPT

Here is the generated PDF with data formatted using Lodash:

Lodash NPM (How It Works For Developers): Figure 3 - PDF Output

Conclusion

Combining Lodash with IronPDF in Node.js allows you to preprocess and transform data efficiently before generating PDF documents. Lodash simplifies data manipulation, making your code more readable and maintainable, while IronPDF provides powerful PDF creation and manipulation capabilities.

IronPDF licensing prices start at just $749.

Darrius Serrant
Full Stack Software Engineer (WebOps)

Darrius Serrant holds a Bachelor’s degree in Computer Science from the University of Miami and works as a Full Stack WebOps Marketing Engineer at Iron Software. Drawn to coding from a young age, he saw computing as both mysterious and accessible, making it the perfect medium for creativity and problem-solving.

At Iron Software, Darrius enjoys creating new things and simplifying complex concepts to make them more understandable. As one of our resident developers, he has also volunteered to teach students, sharing his expertise with the next generation.

For Darrius, his work is fulfilling because it is valued and has a real impact.

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?