Lodash is a JavaScript library that offers utility functions for typical programming tasks using the functional programming model.

The library, which works with web browsers and Node.js, can modify and convert data, perform asynchronous operations, and more.

Learn how to use lodash to manipulate arrays, strings, and objects and find out about its advanced features like function composition.

Getting Started With Lodash

You can add lodash to your app in one of two ways: using a Content Delivery Network (CDN) or installing it using npm or yarn.

To use lodash directly in the browser, copy the lodash CDN link below and insert it in the head section of your HTML file:

        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"
  type="text/javascript"></script>

Using this approach, you can run scripts using lodash in the body of your HTML.

To use lodash in a Node.js project, you should install it in your project directory. You can use either npm or yarn to do so:

        npm install --save lodash
# or
yarn add lodash

You can now use lodash by requiring it in your JavaScript file:

        // Requiring the lodash library
const _ = require("lodash");

// Using the _.sum method
const numbers = [10, 20, 30, 40, 50];
const sum = _.sum(numbers);
console.log(sum);

To run your JavaScript file, enter the node command:

        node [Your script name]

Array Manipulation in Lodash

Lodash comes with a set of methods for array manipulation that provide functionality beyond JavaScript’s built-in Array class.

.chunk

This method divides an array into groups of smaller arrays of a given size. The final chunk may be smaller than the size you request.

Here’s an example:

        const array = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ];
const newArray = _.chunk(array, 2)
console.log(newArray)

// Output:
// [ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ], [ 'g' ] ]

.concat

This method generates a new array by concatenating values to the end of an existing array.

For example:

        const array = [ 1, 2, 'a' ];
const newArray = _.concat(array, 5, 'b', [ 8 ], [ [ 9 ] ]);
console.log(newArray);

// Output:
// [ 1, 2, 'a', 5, 'b', 8, [ 9 ] ]

.join

This method returns a string by combining elements of an array. It joins them using a delimiter that you pass as a parameter when calling the method. The default delimiter it uses is a comma:

        const array = [ "l", "o", "d", "a", "s", "h" ];
const newArray = _.join(array);
console.log(newArray);

// Output:
// l,o,d,a,s,h

const newArray = _.join(array, "-");
console.log(newArray);

// Output:
// l-o-d-a-s-h

String Manipulation in Lodash

With bare JavaScript, string formatting is a simple process. But lodash makes it even easier.

Some of the most common string manipulation operations you can perform with lodash include:

.startsWith and .endsWith

These two methods check if a string starts or ends with a substring, respectively. Both methods return a boolean value of true or false.

For example:

        const string = "lodash";

console.log(_.startsWith(string, "l"));
// Output: true

console.log(_.startsWith(string, "o"));
// Output: false

console.log(_.endsWith(string, "m"));
// Output: false

console.log(_.endsWith(string, "h"));
// Output: true

.repeat

This method repeatedly prints a string a specific number of times. It takes the string as its first argument and the number of repetitions as the second:

        const string = "lodash"
const newString = _.repeat(string, 3);
console.log(newString);
// Output: lodashlodashlodash

.trim

This method removes leading and trailing whitespace. You can also use it to remove any specific characters at the beginning and the end of a string.

For example:

        // Removing leading & trailing whitespace
const string = " bar "
const newString = _.trim(string)
console.log(newString);
// Output: bar

// Removing specified characters
const string = ",bar,"
const newString = _.trim(string, ",")
console.log(newString);
// Output: bar

Object Manipulation in Lodash

Below are some examples of string manipulation that you can perform with lodash:

.merge

The _.merge() method creates a new object by combining the properties of the input objects. A property's value from the later object will replace the value from the earlier object if the property is present in more than one object.

For example:

        const books = {
    'Mathematics': 4,
    'Science': 7
};
   
const notes = {
    'Science': 3 ,
    'Chemistry': 5
};

_.merge(books, notes);
console.log(books);
// Output:
// { Mathematics: 4, Science: 3, Chemistry: 5 }

In this example, the method adds the ‘Chemistry’ property from the second object and overwrites the value of the first object’s ‘Science’ property.

.has

This method returns true if a given series of properties exist in an object and false otherwise.

For example:

        const books = {
    'Mathematics': 4,
    'Science': 7
};

console.log(_.has(books, "Mathematics"));
// Output: true

.omit

This method returns a new object by removing specified properties from the given one.

For example:

        var books = {
    'Mathematics': 4,
    'Science': 3 ,
    'Chemistry': 5
};
   
console.log(_.omit(books, "Science"));
// Output: { Mathematics: 4, Chemistry: 5 }

Function Composition in Lodash

Function composition is a technique you can use in a functional programming language. It involves combining two or more functions into a new function by calling each function in a particular order. This feature enables you to create more complex logic from simpler functions.

To apply this technique, lodash comes with the _.flow and _.flowRight functions. The _.flow() function accepts a list of functions as arguments and outputs a new function that applies the functions in the same order that you pass them in. The _.flowRight() function does the same, but it calls the functions in reverse.

For example:

        function addFive(number) {
    return number + 5
}

function timesTwo(number) {
    return number * 2
}

const addFiveAndTimesTwo = _.flow([addFive, timesTwo]);

const addFiveAndTimesTwoReverse = _.flowRight([addFive, timesTwo]);

console.log(addFiveAndTimesTwo(3));
// Output: 16

console.log(addFiveAndTimesTwoReverse(3));
// Output: 11

The above code defines the functions addFive and timesTwo. The addFive function returns the result of adding 5 to a given number. The timesTwo function multiplies an input number by 2 and returns the result.

The code then uses the _.flow() function to combine the two others and produce the new function, addFiveAndTimesTwo. This new function will first perform the addFive operation on its argument before performing the timesTwo operation on the final result.

The _.flowRight() function produces a new function that does the same as flow, but in reverse.

Finally, this code calls the two new functions, passing 3, as the argument, and logs the results to the console.

The Benefits of Working With Lodash

You can use lodash to simplify your code and make your projects more flexible and maintainable. Its broad range of utility functions, widespread adoption, and regular updates will help you write elegant, effective code. You can use lodash to guarantee your code is always current and compatible with contemporary browsers.