Trusted answers to developer questions
Trusted Answers to Developer Questions

RELATED TAGS

What is Lodash?

Educative Answers Team

Lodash is a JavaScript library that provides utility functions for common programming tasks using a functional programming paradigm; it builds upon the older underscore.js library.

Lodash has several built-in utility functions that make coding in JavaScript easier and cleaner. Instead of writing common functions, again and again, the task can be accomplished with a single line of code.

svg viewer

Installation

Lodash can be installed via NPM:

npm install --save lodash

After installation is complete, Lodash can be imported into a JavaScript file as:

import _ from "lodash"

Now, all of Lodash’s functions can be accessed by the underscore operator.

Functions

Some handy functions included in Lodash are:

_.concat()

The _.concat() function​ simply concatenates values to an existing array, as shown below:

let arr = ['dog', 'cat', 'bird', 'hamster']
let arr = _.concat(arr, 'zebra', 'snake');
// Output => arr = ['dog', 'cat', 'bird', 'hamster', 'zebra', 'snake']

_.find()

Instead of using a loop to iterate through an array to search for an object, the _.find() function can perform the same task in a single line. Moreover, it can be used to find an object using multiple properties.

let friendlist = [
  { firstName: "Jennifer", lastName: "Lawrece", age: 28, gender: "female" },
  { firstName: "Brad", lastName: "Pitt", age: 5, gender: "male" },
  { firstName: "Quentin", lastName: "Tarantino", age: 54, gender: "male" },
  { firstName: "Kate", lastName: "Winslet", age: 40, gender: "female" }
];

let user = _.find(friendlist, {lastName: "Pitt"});
// user -> { firstName: "Brad", lastName: "Pitt", age: 5, gender: "male" }

let overFifty = _.find(users, function(user) {
	return friendlist.age > 50; // return friends who are over 50
});
// overFifty -> { firstName: "Quentin", lastName: "Tarantino", age: 54, gender: "male" }

_.intersection

The normal code, to find the common elements between two arrays, uses a for loop with several lines of code. In Lodash, this is achieved in a single line with the _.intersection() function:

let arr1 = ["football", "cricket", "tennis", "squash"]
let arr2 = ["cricket", "rugby", "badminton", "tennis"]

let commonElements = _.intersection(arr1, arr2);
// commonElements-> ["cricket", "tennis"] 

More functions and information on Lodash can be found in the​ official documentation.

RELATED TAGS

Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2