DEV Community

Leo Kalshteyn
Leo Kalshteyn

Posted on

Lodash Intro

I recently came upon a JS library called Lodash for a small app I am working on which supplies utility functions and readability of objects, arrays, string etc. There are more than 100 functions already added and split into 13 categories which simplify common problems. As hinted by the name, Lodash means, essentially, an underscore


With npm:

$ npm install lodash

And then import it at the top of your JavaScript file in which you would like to use it.

import _ from Lodash


Here are some of the functions that Lodash provides:


Iterating over an array of an object with Lodash looks like:

const data = [
    name: 'Bob',
    age: '25',
    name: 'Will',
    age: '24',
    name: 'Mary',
    age: '26',
];, 'name');
// [ 'Bob', 'Will', 'Mary' ]
Enter fullscreen mode Exit fullscreen mode


This method recursively clones the whole object, so if any property of the resultant object changes, it will not change the original object as the references will also be new.

const users = [
    name: 'Bob', age: '25', profile: { experience: 3 }
    name: 'Will', age: '24', profile: { experience: 2 }
    name: 'Mary', age: '26', profile: { experience: 4 }

const usersClone = _.cloneDeep(users);
usersClone[0].age = '27';

// 27
// 25
Enter fullscreen mode Exit fullscreen mode


In this example you have two separate arrays with different ingredients in each and want to know which ones come up in both.

It would look like this in JS:

let array1 = ["pizza", "icecream", "salads"];
let array2 = ["burger","hotdog", "pasta"];

let commonResults = [];

for (let i = 0; I < array1.length; i++) [
  if (array2.indexOf(array1[i]) !== -1) {
    let indexPosition = array2.indexOf(array1[i]);

Enter fullscreen mode Exit fullscreen mode

In lodash you can simply do:

console.log(_.intersection(array1, array2));
Enter fullscreen mode Exit fullscreen mode

This is just a brief overview of Lodash and some of its utility functions. On the official site, you can read more documentation.


Discussion (0)