Extremely Useful Lodash Methods For JavaScript Developers

Extremely Useful Lodash Methods For JavaScript Developers

Written by Yogesh Chavan on Jun 2nd, 2021 Views Report Post

According to the State of Javascript 2020 Survey results, Lodash is the second most widely used utility library in the world as it provides a lot of methods that make coding easy and fast.

In this article we will see, some of the most useful methods provided by lodash which makes coding easy.

So let's get started.

Installation

  • Using CDN:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
  • Using npm:
npm install --save lodash

Let’s explore some of the most useful methods provided by lodash.

isEqual

The isEqual method performs a deep comparison between two values.

Syntax:

_.isEqual(value, other)

Take a look at the below code:

const obj1 = {
  name: 'Ram',
  age: 20,
  location: {
    city: 'NY',
    state: 'NY'
  }
};

const obj2 = {
  name: 'Ram',
  age: 20,
  location: {
    city: 'NY',
    state: 'NY'
  }
};

console.log(_.isEqual(obj1, obj2)); // true

Here's a Code Pen Demo.

Real Life Application

If you are showing user profile data pre-filled when the user logs in to the system and if you are making a web service API call to save the changed user details when the user clicks on the save button, you can easily check if the user has changed something or not before making API call using lodash’s isEqual method.

Performance

isEqual is much faster than other alternatives when comparing two deeply nested objects. The other ways of comparing two objects are manually comparing each property or using the JSON.stringify method.

isEmpty

The isEmpty method checks if value is an empty object, collection, map, or set.

Syntax:

_.isEmpty(value)

Take a look at the below code:

const obj1 = { name: 'David' };
console.log(_.isEmpty(obj1)); // false

const obj2 = {};
console.log(_.isEmpty(obj2)); // true

const array1 = [];
console.log( _.isEmpty(array1)); // true

const array2 = [2, 3];
console.log(_.isEmpty(array2)); // false

const nullValue = null;
console.log(_.isEmpty(nullValue)); // true

const undefinedValue = undefined;
console.log(_.isEmpty(undefinedValue)); // true

Here's a Code Pen Demo.

As you can see the isEmpty method quickly allows testing for an empty value. Instead of using Object.keys(obj1).length === 0 to check for an empty object, isEmpty makes it easy to perform the check.

get

The get method gets the value at the path of an object. If the resolved value is undefined, the defaultValue is returned in its place.

Syntax:

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

Take a look at the below code:

const user = {
      "gender": "male",
      "name": {
        "title": "mr",
        "first": "brad",
        "last": "gibson"
      },
      "location": {
        "street": "9278 new road",
        "city": "kilcoole",
        "state": "waterford",
        "postcode": "93027",
        "coordinates": {
          "latitude": "20.9267",
          "longitude": "-7.9310"
        },
        "timezone": {
          "offset": "-3:30",
          "description": "Newfoundland"
        }
      }
};

console.log(_.get(user, 'location.timezone', {})); // {'offset':'-3:30','description':'Newfoundland'}
console.log(_.get(user, 'name.middlename', '')); // ''

Here's a Code Pen Demo.

The great thing about lodash’s get method is that, if the location property does not exist in the user object, directly accessing it as user.location.timezone will throw an error but If lodash’s get method is used, it will not throw an error but will return the default value.

const user = {
      "gender": "male",
      "name": {
        "title": "mr",
        "first": "brad",
        "last": "gibson"
      }
};

// This will work and will return the default value specified
console.log('timezone:',_.get(user, 'user.location.timezone', '')); 
// Error: Cannot read property 'timezone' of undefined
console.log('timezone:',user.location.timezone);

sortBy

The sortBy method creates an array of elements, sorted in ascending order by the results of running each element in a collection through each iteratee.

Syntax:

_.sortBy(collection, [iteratees=[_.identity]])

Take a look at the below code:

const users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];

//sort users by age
console.log(_.sortBy(users, [function(user) { return user.age }])); 
// output: [{'user':'barney','age':34},{'user':'barney','age':36},{'user':'fred','age':40},{'user':'fred','age':48}]

Here's a Code Pen Demo.

orderBy

The orderBy method is similar to sortBy but it allows us to specify the descending or ascending sort order. For descending sort, we specify desc and for ascending we specify asc.

Syntax:

_.orderBy(collection, [iteratees=[_.identity]], [orders])

Take a look at the below code:

const users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];

// sort by user in descending order
console.log(_.orderBy(users, ['user'], ['desc']));

// sort by user in ascending order and age by descending order
console.log(_.orderBy(users, ['user', 'age'], ['asc', 'desc']));

Here's a Code Pen Demo.

union

The union method returns the unique values from all the arrays passed.

Syntax:

_.union([arrays])

Take a look at below code:

console.log(_.union([1], [1, 2, 3], [-1, 0, 4], [2, 2, 3])); // [1, 2, 3, -1, 0, 4]

Here's a Code Pen Demo.

cloneDeep

The cloneDeep method returns a clone/copy of an object recursively. This is very useful if you don’t want to change the original object but create a copy of the object to add extra properties to it.

Syntax:

_.cloneDeep(value)

Take a look at the below code:

const obj = {
  name: {
    title: "Ms",
    first: "Hannah",
    last: "Ennis"
  },
  location: {
    city: "Flatrock",
    state: "British Columbia",
    country: "Canada",
    postcode: "P1X 7D3",
    coordinates: {
      latitude: "-62.3907",
      longitude: "37.8088"
    },
    timezone: {
      offset: "+5:30",
      description: "Bombay, Calcutta, Madras, New Delhi"
    }
  }
};
const clone = _.cloneDeep(obj);

console.log(obj.name === clone.name); // false
console.log(clone === obj); // false

Here's a Code Pen Demo.

As you can see from the above comparison of clone.name and obj.name, _.cloneDeep creates totally different object which is a copy/clone.

debounce

The debounce method is the most useful lodash method and it allows us to call a function after some milliseconds have passed.

Syntax:

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

Note: the debounce method returns a function that we invoke to make subsequent calls.

This is a very useful method that allows us to minimize the number of API calls to the server.

Let’s build a search functionality where a user types some information as input, and we will make an API call to the server to get the result based on the input.

Demo without using debouncing

In the above without debouncing example, you can see that on every keystroke, we are making an API call.

So we are unnecessarily increasing the server API calls. If the server is taking more time to return the data, you might see the previous result even when you are expecting new results based on your input value.

To fix this we can use debouncing where we only make an API request after 300 milliseconds once a user has stopped typing which is more beneficial. It will save from unnecessary requests and will also save from previous API call result being displayed for a short amount of time.

Demo using debouncing

In the above code, the debounce method returns a function which we’re storing in debFunction variable.

const debFunction = _.debounce(onSearchText, 300);

Then for every key change event, we’re calling the function stored in debFunction variable after 300 milliseconds once the user has stopped typing. Calling debFunction, internally, calls the onSearchText function where we're actually making an API call.

Want to know how to use debouncing to improve the performance of your search in React application? Check out my this article.

You can explore all other methods of lodash HERE.

Thanks for reading!

Check out my recently published Mastering Redux course.

In this course, you will learn:

  • Basic and advanced Redux
  • How to manage the complex state of array and objects
  • How to use multiple reducers to manage complex redux state
  • How to debug Redux application
  • How to use Redux in React using react-redux library to make your app reactive.
  • How to use redux-thunk library to handle async API calls and much more

and then finally we'll build a complete food ordering app from scratch with stripe integration for accepting payments and deploy it to the production.

Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.

Comments (0)