Lodash is one of the best utility libraries that every JavaScript programmer should know.

In this article, I'll show you 11 useful Lodash functions with examples.

Let's dive right in.

1. Filter a List

I use this method a lot when I developed the search function for an eCommerce site. The search result should be displayed based on selected criteria.

Lodash makes it ease. Given that you want to show a list of fiction books, then:

_.filter(books: { genre: 'fiction' });

When you have to deal with a complex condition, you can pass the second parameter as a function.

The below example is showing you how to filter fiction books that cost greater than $7.5

_.filter(books: function(book) {
  return book.genre === 'fiction' && book.price > 7.5;
});

2. Generate Random Numbers

Seems like generating random things is one of the common tasks we have to deal with.

If you want to generate a random number from 1 to 10 with pure JavasScript, here's what you can do:

Math.floor(Math.random() * 10) + 1;

Could it be simpler? Yes.

In Lodash, it's just:

_.random(1, 10);

And for floating number, from 2.5 to 5.5 for example, here you are:

_.random(2.5, 5.5);

3. Loop with Times

I found times function is very useful when combining it with random function to generate an array of random numbers.

Of course, you can do it with for or while. However, code should be shorter with times.

function getRandomNumber() {
  return _.random(1, 10);
}
let randomNumbers = _.times(10, getRandomNumber);
console.log(randomNumbers); // example: [9, 5, 2, 6, 2, 1, 5, 3, 1, 8]

4. Clone an Object

I used to clone a JavaScript object the hard way. It's not straightforward. You may face this issue too.

When it comes to Lodash, this task turns out to be a piece of cake.

For example, you want to create another book object with the same value of the given book:

let book = {
  name: 'JavaScript: The Good Parts',
  price: 13.5
};
let clonedBook = _.clone(book);

It's easy right.

But be careful when you clone a list of objects:

let books = [{
  name: 'JavaScript: The Good Parts',
  price: 13.5
}, {
  name: 'Learn JavaScript Visually',
  price: 15
}];
let clonedBooks = _.clone(books);

What's the problem here?

The corresponding objects in books and clonedBooks now are still holding the same reference. I mean if you change books[0].name to Learning React Native then clonedBooks[0] should be Learning React Native too.

Kind of subtle issue, huh?

How do we fix it?

That's when the deep clone function comes in.

So instead of:

let clonedBooks = _.clone(books);

Now, we will use:

let clonedBooks = _.cloneDeep(books);

And the problem is solved.

5. Compare Two Objects

What do you usually do if you want to compare two objects? Compare every single property or using JSON.stringify

Have you tried Lodash's isEqual? You may not see the significant value of it until you have to handle deeply nested objects.

With just a simple call, isEqual will take the comparison to the deep level.

let book1 = {
  name: 'JavaScript: The Good Parts',
  price: 13.5
};
let book2 = {
  name: 'JavaScript: The Good Parts',
  price: 13.5
};
console.log(_.isEqual(book1, book2)); // true

6. Pick Properties

This function is useful when you want to form a new object based on the properties of the existing object.

For example, you want to create a new product with two properties name and price. All you have to do is picking the properties and leave the rest to Lodash.

let product = {
  name: 'Learning React Native',
  category: 'Book',
  price: 15,
  discount: 0.3
};
let newProduct = _.pick(product, ['name', 'price']);
console.log(newProduct); // { name: 'Learning React Native, price: 15 }

You can also excuse this task in an inverted manner by using omit function:

let product = {
  name: 'Learning React Native',
  category: 'Book',
  price: 15,
  discount: 0.3
};
let newProduct = _.omit(product, [category, discount]);
console.log(newProduct); // { name: 'Learning React Native, price: 15 }

7. Get/Set Property's Value

What happens if you use an undefined property of an object? It will throw an error like below:

let book = {
  name: 'Learning JavaScript'
};
let discountPrice = book.price.discount; // Uncaught TypeError: Cannot read property 'discount' of undefined

This time we need to use the get function. If a property is undefined, a default value will be returned:

let book = {
  name: 'Learning JavaScript'
};
let discountPrice = _.get(book, 'book.price.discount', 0); // 0

8. Check if a Variable is Empty

You use this function when you want to check if an object, a map, a collection, or a set is empty.

Let's take a look at below:

let book1 = {};
console.log(_.isEmpty(book1)); // true;
let book2 = { name: 'Learning JavaScript };
console.log(_.isEmpty(book2)); // false;
let books1 = [{
  name: 'Learning JavaScript'
}, {
  name: 'Learning React Native'
}];
console.log(_.isEmpty(books1)); // false;
let books2 = [];
console.log(_.isEmpty(books2)); // true;
let nullBook = null;
console.log(_.isEmpty(nullBook)); // true;
let undefinedBook = undefined;
console.log(_.isEmpty(undefinedBook)); // true;

9. Sort a Collection

For example, if you want to search a list of books by price in ascending order, do as below:

let books = [{
  name: 'JavaScript',
  price: 10
}, {
  name: 'C++',
  price: 9
}, {
  name: 'Python',
  price: 14
}, {
  name: 'Golang',
  price: 12
}];
let sortedBook = _.sortBy(books, ['price']);
console.log(sortedBook); // [{ name: 'C++', price: 9 }, { name: 'JavaScript', price: 10 }, { name: 'Golang', price: 12 }, { name: 'Python', price: 14 }]

If you want to control sort order, you can use orderBy function.

let sortedBook = _.orderBy(books, ['price'], ['desc']);
let sortedBook = _.orderBy(books, ['price'], ['asc']);

Or in a combined manner:

let sortedBook = _.orderBy(books, ['price', 'discount'], ['asc', 'desc']);

10. Delay Calling a Function

Assume that you're developing a function just like Google search suggestion — when a user types into the search box, it will drop down a list of suggested terms.

Instead of calling API for every typed character, you should use debounce function to do the task after an amount of time:

function showSuggestedTerms() {
  // Call API and then show the result
}
let searchBox = document.getElementById('search-box');
searchBox.addEventListener('keyup', _.debounce(showSuggestedTerms, 300);

The showSuggestedTerms function above will be called after 300ms when the user stops typing.

11. Merge Arrays

You can use concat method to merge arrays:

let array1 = [1, 5, 3, 1];
let array2 = [7, 25, 21];
let array3 = [11, 3, 3, 2];
let mergedArray = _.concat(array1, array2, array3);
console.log(mergedArray); // [1, 5, 3, 1, 7, 25, 21, 11, 3, 3, 2];

In case you want the element's values of the merged array to be unique, you can use union function:

let mergedArray = _.union(array1, array2, array3);
console.log(mergedArray); // [1, 5, 3, 7, 25, 21, 11, 2]

The above functions are not all but the ones I use most of the time.

I love Lodash. It saves me a lot of time and makes my code more beautiful.

What do you think about this powerful library?