Ebooks

Lodash tutorial

Lodash tutorial covers the Lodash JavaScript library. In this introductory Lodash tutorial, we cover Lodash functions in multiple examples.

Lodash

Lodash is a JavaScript library which provides utility functions for common programming tasks. It uses functional programming paradigm. Lodash was inspired by Underscore.js.

Lodash helps programmers write more concise and easier to maintain JavaScript code. Lodash contains tools to simplify programming with strings, numbers, arrays, functions and objects.

By convention, Lodash module is mapped to the underscore character.

Lodash installation

First, we install the Lodash library.

$ npm init
$ npm i lodash

The Lodash library is installed locally with npm.

$ cat package.json 
{
  "name": "lodashlib",
  "version": "1.0.0",
  "description": "Lodash testing",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "lodash": "^4.17.5"
  }
}

We use Lodash version 4.17.5.

<script src="lodash.js"></script>    

Inside a browser, we include the library in a <script> tag.

Lodash version

In the first example, we determine the version of the Lodash library.

version.js
const _ = require("lodash")

const ver = _.VERSION
console.log(ver);    

The example prints the version of the Lodash library.

const _ = require("lodash")

By convention, the Lodash library is mapped to the underscore character.

const ver = _.VERSION
console.log(ver);    

The version is stored in the VERSION variable.

$ node version.js 
4.17.5

We use Lodash version 4.17.5.

Lodash random number

The _.random() function produces random values between the inclusive lower and upper bounds.

random_vals.js
const _ = require("lodash")

var r = _.random(10);
console.log(r);

r = _.random(5, 10);
console.log(r);

The example prints two random values.

var r = _.random(10);

We produce a random value between 0 and 10.

r = _.random(5, 10);

Here we produce a random value between 5 and 10.

Lodash _.times function

The _.times() executes the function n times.

times_fun.js
const _ = require("lodash");

_.times(4, () => {

    console.log("brave");
})

In the example, we execute the innter function four times. The function prints a word to the console.

$ node times_fun.js 
brave
brave
brave
brave

This is the output.

Lodash determine data type

Lodash contains functions which determine the data type of a value.

datatype.js
const _ = require("lodash");

const vals = [1, 2, 'good', [1, 2], {name: 'Peter', age: 32}];

vals.forEach( (e) => {

    if (_.isNumber(e)) {
        console.log(`${e} is a number`);
    }

    if (_.isString(e)) {
        console.log(JSON.stringify(e) + ' is a string');
    }

    if (_.isArray(e)) {
        console.log(JSON.stringify(e) + ' is an array');
    }

    if (_.isObject(e)) {
        console.log(JSON.stringify(e) + ' is an object');
    }

});

In the example, we determine the data types of the elements of an array.

const vals = [1, 2, 'good', [1, 2], {name: 'Peter', age: 32}];

We have an array of values, including numbers, a string, an array, and an object.

if (_.isNumber(e)) {
    console.log(`${e} is a number`);
}

The _.isNumber() function checks if a value is a number.

if (_.isString(e)) {
    console.log(JSON.stringify(e) + ' is a string');
}

The _.isString() function checks if a value is a string.

if (_.isArray(e)) {
    console.log(JSON.stringify(e) + ' is an array');
}

The _.isArray() function checks if a value is an array.

if (_.isObject(e)) {
    console.log(JSON.stringify(e) + ' is an object');
}

The _.isObject() function checks if a value is an object.

$ node index.js 
1 is a number
2 is a number
"good" is a string
[1,2] is an array
[1,2] is an object
{"name":"Peter","age":32} is an object

This is the output of the program.

Lodash _.range function

The Lodash _.range() function creates an array of numbers. The function accepts the start, end, and step parameters.

range_fun.js
const _ = require("lodash");

const vals = _.range(10);
console.log(vals);

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

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

In the code example, we create three ranges of values.

const vals = _.range(10);

This line creates an array of values 0..9. The end value is mandatory, the start and step are optional. The end is non-inclusive; therefore, value 10 is not included.

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

Here we specify start and step parameters. We create an array of values 0..14.

const vals3 = _.range(0, 15, 5);

Finally, we provide all three parameters. An array of 0, 5, and 10 values is created.

$ node range_fun.js
[ 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 ]

This is the output.

Lodash maximum and minimum

Lodash allows to compute the maximum and minimum values of an array.

min_max.js
const _ = require("lodash");

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);

The example computes the minimum and maximum values of an array.

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

The _.min() function returns the minimum of the array.

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

The ._max() function returns the maximum of the array.

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

max = _.maxBy(obs, 'n');
console.log(max);    

To compute the minimum and maximum of object properties, we use the _.minBy() and .maxBy() functions.

$ node min_max.js 
-12
43
24
{ n: -11 }
{ n: 12 }

This is the output.

Lodash _.sum function

The _.sum() function calculates the sum of array values.

sum_fun.js
const _ = require("lodash");

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.

$ node sum_fun.js 
6

This is the output.

Lodash collection filter

The _.filter() function returns an array of elements for which the predicate function returns true.

col_filter.js
const _ = require("lodash");

const nums = [4, -5, 3, 2, -1, 7, -6, 8, 9];

const pos_nums = _.filter(nums, (e) => e > 0);
console.log(pos_nums);

In the code example, we filter out positive values of an array.

const pos_nums = _.filter(nums, (e) => e > 0);

A predicate is a fuction that returns a boolean value. In our case we have an anonymous function that returns true for values greater than 0.

$ node col_filter.js 
[ 4, 3, 2, 7, 8, 9 ]

This is the output.

Lodash collection partition

The partition operation splits the original collection into a pair of arrays. The first array contains elements for which the specified predicate yields true, while the second list contains elements for which the predicate yields false.

col_partition.js
const _ = require("lodash");

const nums = [4, -5, 3, 2, -1, 7, -6, 8, 9];

const [nums2, nums3] = _.partition(nums, (e) => e < 0);
console.log(nums2);
console.log(nums3);

With the _.partition() function we split the array into two arrays; the first contains positive values, the second one negative valaues.

const [nums2, nums3] = _.partition(nums, (e) => e < 0);

The _.partition() function creates two arrays according to the predicate function. With the array destructuring operation, we assign the created arrays to two variables: nums2 and nums3.

$ node col_partition.js 
[ -5, -1, -6 ]
[ 4, 3, 2, 7, 8, 9 ]

This is the output.

Lodash collection reduce

Reduction is a terminal operation that aggregates list values into a single value. The _.reduce() function applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

col_reduce.js
const _ = require("lodash");

const nums = [4, 5, 3, 2, 1, 7, 6, 8, 9];

const sum = _.reduce(nums, (total, next) => { return total + next });
console.log(sum);

const colours = ["red", "green", "white", "blue", "black"];

const res = _.reduceRight(colours, (next, total) => { return `${total}-${next}` });
console.log(res);

In the example, we use the reduce operation on a list of integers and strings.

const sum = _.reduce(nums, (total, next) => { return total + next });
console.log(sum);

We calculate the sum of values. The total is the accumulator, the next is the next value in the list.

const res = _.reduceRight(colours, (next, total) => { return `${total}-${next}` });

The _.reduceRight() accumulates a value starting with last element and applying the operation from right to left to each element and the current accumulator value.

$ node col_reduce.js 
45
red-green-white-blue-black

This is the output.

Lodash string case

Locash library contains several functions that work with the case of words.

string_case.js
const _ = require("lodash");

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));

In the example, we modify the case of words with _.camelCase(), _.capitalize(), ._kebabCase(), _lowerCase(), and _.upperCase().

$ node string_case.js 
[ 'sky', 'sun', 'blueIsland' ]
[ 'Sky', 'Sun', 'Blue island' ]
[ 'sky', 'sun', 'blue-island' ]
[ 'sky', 'sun', 'blue island' ]
[ 'SKY', 'SUN', 'BLUE ISLAND' ]

This is the output.

Lodash string _.startsWith and _.endsWith

The _.startsWith() function determines if the string starts with the specified string. The _.endsWith() function determines if the string ends with the specified string.

string_startend.js
const _ = require("lodash");

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);
    }
});

In the example, we print the words that start with 't' and end with 'k'.

$ nodejs string_startend.js 
Starting with 't'
tank
tourist
ten
Ending with 'k'
tank
ink

This is the output.

Lodash string padding

Strings can be padded with a character if they are shorter than a specified number.

string_pad.js
const _ = require("lodash");

const nums = [657, 122, 3245, 345, 99, 18];

nums.forEach( e => {

    console.log(_.padStart(e.toString(), 20, '.'));
});

The example pads numbers with a dot character using _.padStart().

$ node string_pad.js 
.................657
.................122
................3245
.................345
..................99
..................18

This is the output.

Lodash object keys and values

The _.keys() function returns an array of the property names of the JavaScript object and the _.values() function returns an array of their values.

keys_values.js
const _ = require("lodash");

const p = {age: 24, name: "Rebecca", occupation: "teacher"};

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

const values = _.values(p);
console.log(values);

In the example, we print the keys and values of a person object.

$ node keys_values.js 
[ 'age', 'name', 'occupation' ]
[ 24, 'Rebecca', 'teacher' ]

This is the output.

Lodash iterate object properties

The _.forIn() function can be used to iterate over object properties.

iter_object_props.js
const _ = require("lodash");

const p = {age: 24, name: "Rebecca", occupation: "teacher"};

_.forIn(p, (value, key) => {

    console.log(`${key}: ${value}`);
})

In the example, we iterate over properties of a person object using _.forIn().

$ node iter_object_props.js 
age: 24
name: Rebecca
occupation: teacher

This is the output.

In this tutorial, we have introduced the Lodash JavaScript library.

You might also be interested in the following related tutorials: JSON Server tutorial, Moment.js tutorial, Reading JSON from URL in JavaScript, JavaScript Snake tutorial, JQuery tutorial, jQuery Autocomplete tutorial, or Using jQuery DatePicker.