Google News
logo
Lodash Interview Questions
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.
Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc.

Lodash’s modular methods are great for :
 
* Iterating arrays, objects, & strings
* Manipulating & testing values
* Creating composite functions
We can directly use the file in the browser. Go to the official documentation and copy the lodash.min.js file CDN link and paste this link inside the head section.

Install :

In a browser :
<script src="lodash.js"></script>

(or)

<script type=”text/JavaScript” src = “https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js”></script>

Using npm :

$ npm i -g npm

$ npm i --save lodash

 

In Node.js :

// Load the full build.

var _ = require('lodash');

// Load the core build.

var _ = require('lodash/core');

// Load the FP build for immutable auto-curried iteratee-first data-last methods.

var fp = require('lodash/fp');

 

// Load method categories.

var array = require('lodash/array');

var object = require('lodash/fp/object');

 

// Cherry-pick methods for smaller browserify/rollup/webpack bundles.

var at = require('lodash/at');

var curryN = require('lodash/fp/curryN');

Note :

Install n_ for Lodash use in the Node.js < 6 REPL.

 

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc. Lodash Array methods are used to perform operations on arrays using inbuild methods.

* Lodash _.chunk() Method
* Lodash _.compact() Method
* Lodash _.concat() Method
* Lodash _.difference() Method
* Lodash _.differenceBy() Method
* Lodash _.differenceWith() Method
* Lodash _.drop() Method
* Lodash _.dropRight() Method
* Lodash _.dropRightWhile() Method
* Lodash _.dropWhile() Method
* Lodash _.fill() Method
* Lodash _.findIndex() Method
* Lodash _.findLastIndex() Method
* Lodash _.first() Method
* Lodash _.flatten() Method
* Lodash _.flattenDepth() Method
* Lodash _.flattenDeep() method
* Lodash  _.fromPairs() Method
* Lodash  _.head() Method
* Lodash _.indexOf() Method
* Lodash _.initial() Method
* Lodash _.Intersection() Method
* Lodash _.intersectionBy() Method
* Lodash _.Intersection() Method
* Lodash _.join() Method
* Lodash _.last() Method
* Lodash _.lastIndexOf() Method
* Lodash  _.nth() Method
* Lodash  _.pull() Method
* Lodash _.pullAll() Method
* Lodash _.pullAllBy() Method
* Lodash _.pullAllWith() Method
* Lodash _.pullAt() Method
* Lodash _.remove() Method
* Lodash _.reverse() Method
* Lodash _.slice() Method
* Lodash _.sortedIndex() Method
* Lodash _.sortedIndexBy() Method
* Lodash _.sortedIndexOf() Method
* Lodash _.sortedLastIndex() Method
* Lodash _.sortedLastIndexBy() Method
* Lodash _.sortedLastIndexOf() Method
* Lodash _.sortedUniq()Method
* Lodash _.sortedUniqBy() Method
* Lodash _.tail() Method
* Lodash _.take() Method
* Lodash _.takeRight() Method
* Lodash _.takeRightWhile() Method
* Lodash _.takeWhile() Method
* Lodash _.union() Method
* Lodash _.unionBy() Method
* Lodash _.unionWith() Method
* Lodash _.uniq() Method
* Lodash _.uniqBy() Method
* Lodash _.uniqWith() Method
* Lodash _.unzip() Method
* Lodash _.unzipWith() Method
* Lodash _.without() Method
* Lodash _.xor() Method
* Lodash _.xorBy() Method
* Lodash _.xorWith() Method
* Lodash _.zip() Method
* Lodash _.zipObject() Method
* Lodash _.zipObjectDeep() Method
* Lodash _.zipWith() Method
Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).
_.now()
_.defer(function(stamp) {
  console.log(_.now() - stamp);
}, _.now());
// => Logs the number of milliseconds it took for the deferred invocation.
The _.assign method is the equivalent of the spread operator from ES6. It’s pretty easy to understand, it assigns properties of one or many objects to a source object.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
    <script type="text/javascript">
        var foo = {
            a: "a property"
        };
        var bar = {
            b: 4,
            c: "an other property"
        }

        var result = _.assign({
            a: "an old property"
        }, foo, bar);

        console.log(JSON.stringify(result));
    </script>
</head>
<body></body>
</html>
Output :
{"a":"a property","b":4,"c":"an other property"}
The _.chunk() function creates an array of elements split into groups the length of the specified size.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
    <script type="text/javascript">
  // Lodash chunking array
        nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

        let c1 = _.chunk(nums, 2);
        console.log(c1);

        let c2 = _.chunk(nums, 3);
        console.log(c2);
    </script>
</head>
<body></body>
</html>
Output :
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Instead of iterating through an array with a loop to find a specific object, we can simply use a _.find method.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
    <script type="text/javascript">
  // Lodash first and last array elements
  var users = [
    { firstName: "John", lastName: "Doe", age: 28, gender: "male" },
    { firstName: "Jane", lastName: "Doe", age: 5, gender: "female" },
    { firstName: "Jim", lastName: "Carrey", age: 54, gender: "male" },
    { firstName: "Kate", lastName: "Winslet", age: 40, gender: "female" }
  ];

  var user = _.find(users, { lastName: "Doe", gender: "male" });
  console.log(user);
  // user -> { firstName: "John", lastName: "Doe", age: 28, gender: "male" }

  var underAgeUser = _.find(users, function(user) {
   return user.age < 18;
  });
  
  console.log(underAgeUser);
    </script>
</head>
<body></body>
</html>
Output :
{firstName: "John", lastName: "Doe", age: 28, gender: "male"}
{firstName: "Jane", lastName: "Doe", age: 5, gender: "female"}
The .first()/.head() functions return the first array element; the _.last() function returns the last array element.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
    <script type="text/javascript">
  // Lodash first and last array elements
        words = ['sky', 'wood', 'forest', 'falcon',
            'pear', 'ocean', 'universe'
        ];

        let fel = _.first(words);
        let lel = _.last(words);

        console.log(`First element: ${fel}`);
        console.log(`Last element: ${lel}`);
    </script>
</head>
<body></body>
</html>
Output :
First element: sky
Last element: universe
The _.slice() method gets a slice from an array. It takes two indexes: the starting and ending index, where the starting index is inclusive and the ending is exclusive.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
    <script type="text/javascript">
  // Getting array slice
        nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

        let c2 = _.slice(nums, 2, 6);
        console.log(c2);

        let c3 = _.slice(nums, 0, 8);
        console.log(c3);
    </script>
</head>
<body></body>
</html>
Output :
[3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
The _.random() function produces random values between the inclusive lower and upper bounds.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
    <script type="text/javascript">
  // Getting array slice
  var r = _.random(15);
  console.log(r);

  r = _.random(5, 15);
  console.log(r);
    </script>
</head>
<body></body>
</html>
Output :
8
7
Lodash allows computing the maximum and minimum values of an array.

Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  const vals = [-3, 4, 0, 12, 43, 9, -12];

  var min = _.min(vals);
  console.log(min);

  var max = _.max(vals);
  console.log(max);

  max = _.max(_.range(5, 25));
  console.log(max);

  const obs = [{n: 12}, {n: -4}, {n: 4}, {n: -11}];

  min = _.minBy(obs, 'n');
  console.log(min);

  max = _.maxBy(obs, 'n');
  console.log(max);
    </script>
</head>
<body></body>
</html>
Output :
-12
43
24
{ n: -11 }
{ n: 12 }
 
The _.sum() function calculates the sum of array values.
Example :
const vals = [-2, 0, 3, 7, -5, 1, 2];

const sum = _.sum(vals);
console.log(sum);
In the code example, we compute and print the sum of array values.
6
The Lodash _.range() function creates an array of numbers. The function accepts the start, end, and step parameters.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  const vals = _.range(10);
  console.log(vals);

  const vals2 = _.range(0, 15);
  console.log(vals2);

  const vals3 = _.range(0, 15, 5);
  console.log(vals3);
    </script>
</head>
<body></body>
</html>
Output :
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
[ 0, 5, 10 ]
The _.delay() function delays the execution of a function for the specified amount of milliseconds.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  function message()
  {
   console.log("Some message");
  }
  _.delay(message, 150);
  console.log("Some other message");
    </script>
</head>
<body></body>
</html>
 
The example outputs two messages. The first one is delayed for 150ms. Here is the output :

Some other message
Some message
The _.times() executes the function n times.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  _.times(4, () => {
   console.log("Learning");
  })
    </script>
</head>
<body></body>
</html>
 
In the example, we execute the inner function four times. The function prints a word to the console.
Learning
Learning
Learning
Learning
_.reduce is a little bit like a filter function. The only difference is that you can choose the form of the returned object.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  var users = [
   { name: "John", age: 30 },
   { name: "Jane", age: 28 },
   { name: "Bill", age: 65 },
   { name: "Emily", age: 17 },
   { name: "Jack", age: 30 }
  ]

  var reducedUsers = _.reduce(users, function (result, user) {
   if(user.age >= 18 && user.age <= 59) {
    (result[user.age] || (result[user.age] = [])).push(user);
   }
    
   return result;
  }, {});
  
  console.log(JSON.stringify(reducedUsers));
    </script>
</head>
<body></body>
</html>
The above HTML prints below output on the console :
{"28":[{"name":"Jane","age":28}],"30":[{"name":"John","age":30},{"name":"Jack","age":30}]}
_.keyBy is a very useful method. It helps a lot when trying to get an object with a specific property. Let’s say we have 100 users and we want to get the user with Id 1.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
        var users = [
    { id: 1, firstName: "John", lastName: "Doe", age: 28, gender: "male" },
    { id : 2, firstName: "Jane", lastName: "Doe", age: 5, gender: "female" },
    { id : 3, firstName: "Jim", lastName: "Carrey", age: 54, gender: "male" },
    { id : 4, firstName: "Kate", lastName: "Winslet", age: 40, gender: "female" }
        ];
        
        users = _.keyBy(users, "id");
  
        var user = users[1];
        console.log(user);
    </script>
</head>
<body></body>
</html>
Output :
{id: 1, firstName: "John", lastName: "Doe", age: 28, gender: "male"}
The _.shuffle() function shuffles a collection.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  words = ['sky', 'wood', 'forest', 'falcon', 
   'pear', 'ocean', 'universe'];

  console.log(_.shuffle(words));
  console.log(_.shuffle(words));
  console.log(_.shuffle(words));
  console.log(words);
    </script>
</head>
<body></body>
</html>
Output :
["universe", "pear", "ocean", "sky", "wood", "falcon", "forest"]
["forest", "pear", "ocean", "falcon", "wood", "universe", "sky"]
["ocean", "sky", "wood", "universe", "pear", "forest", "falcon"]
["sky", "wood", "forest", "falcon", "pear", "ocean", "universe"]
Locash library contains several functions that work with the case of words :

* _.camelCase
* _.capitalize
* _.kebabCase
* _.lowerCase
* _.upperCase

<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  const words = ["sky", "Sun", "Blue Island"];

  console.log(_.map(words, _.camelCase));
  console.log(_.map(words, _.capitalize));
  console.log(_.map(words, _.kebabCase));
  console.log(_.map(words, _.lowerCase));
  console.log(_.map(words, _.upperCase));
    </script>
</head>
<body></body>
</html>
Output :
[ 'sky', 'sun', 'blueIsland' ]
[ 'Sky', 'Sun', 'Blue island' ]
[ 'sky', 'sun', 'blue-island' ]
[ 'sky', 'sun', 'blue island' ]
[ 'SKY', 'SUN', 'BLUE ISLAND' ]
The _.startsWith() function determines if the string starts with the specified string. The _.endsWith() function determines if the string ends with the specified string.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  const words = ["tank", "boy", "tourist", "ten",
    "pen", "car", "marble", "sonnet", "pleasant",
    "ink", "atom"]

  console.log("Starting with 't'");
  words.forEach( e => {

   if (_.startsWith(e, 't')) {

    console.log(e);
   }
  });

  console.log("Ending with 'k'");
  words.forEach( e => {

   if (_.endsWith(e, 'k')) {

    console.log(e);
   }
  });
    </script>
</head>
<body></body>
</html>
Output :
Starting with 't'
tank
tourist
ten
Ending with 'k'
tank
ink
The _.keys() function returns an array of the property names of the JavaScript object and the _.values() function returns an array of their values.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
        // using Object Literals
        var user = {
            firstName: 'FreeTime',
            lastName: 'Learn',
            emailId: 'freetimelearn@gmail.com',
            age: 31,
            getFullName: function () {
                return user.firstName + " " + user.lastName;
            }
        }

        const keys = _.keys(user);
        console.log(keys);

        const values = _.values(user);
        console.log(values);
    </script>
</head>
<body></body>
</html>
Output :

Lodash
The _.forIn() function can be used to iterate over object properties.
Example :
<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
        // using Object Literals
        var user = {
            firstName: 'Free Time',
            lastName: 'Learning',
            emailId: 'info@freetimelearning.com',
            age: 31
        }

        _.forIn(user, (value, key) => {
            console.log(`${key}: ${value}`);
        })
    </script>
</head>
<body></body>
</html>
Output :

Lodash iterate object properties
* Lodash _.add() Method

*
Lodash _.ceil() Method

*
Lodash _.divide() Method

*
Lodash _.floor() Method

*
Lodash _.max() Method

*
Lodash _.maxBy() Method

*
Lodash _.mean() Method

*
Lodash _.meanBy() Method

*
Lodash _.min() Method

*
Lodash _.minBy() Method

*
Lodash _.multiply() Method

*
Lodash _.round() Method

*
Lodash _.subtract() Method

*
Lodash _.sum() Method

*
Lodash _.sumBy() Method

Refernces : Lodash, Lodash Doc