<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
.
_.now()
_.defer(function(stamp) {
console.log(_.now() - stamp);
}, _.now());
// => Logs the number of milliseconds it took for the deferred invocation.
_.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.<!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>
{"a":"a property","b":4,"c":"an other property"}
_.chunk()
function creates an array of elements split into groups the length of the specified size.<!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>
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
_.find
method.<!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>
{firstName: "John", lastName: "Doe", age: 28, gender: "male"}
{firstName: "Jane", lastName: "Doe", age: 5, gender: "female"}
.first()/.head()
functions return the first array element; the _.last()
function returns the last array element.<!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>
First element: sky
Last element: universe
_.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.<!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>
[3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
_.random()
function produces random values between the inclusive lower and upper bounds.<!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>
8
7
<!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>
-12
43
24
{ n: -11 }
{ n: 12 }
_.sum()
function calculates the sum of array values.const vals = [-2, 0, 3, 7, -5, 1, 2];
const sum = _.sum(vals);
console.log(sum);
6
_.range()
function creates an array of numbers. The function accepts the start, end, and step parameters.<!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>
[ 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 ]
_.delay()
function delays the execution of a function for the specified amount of milliseconds.<!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>
_.times()
executes the function n times.<!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>
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.<!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>
{"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.<!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>
{id: 1, firstName: "John", lastName: "Doe", age: 28, gender: "male"}
_.shuffle()
function shuffles a collection.<!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>
["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"]
_.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>
[ 'sky', 'sun', 'blueIsland' ]
[ 'Sky', 'Sun', 'Blue island' ]
[ 'sky', 'sun', 'blue-island' ]
[ 'sky', 'sun', 'blue island' ]
[ 'SKY', 'SUN', 'BLUE ISLAND' ]
_.startsWith()
function determines if the string starts with the specified string. The _.endsWith()
function determines if the string ends with the specified string.<!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>
Starting with 't'
tank
tourist
ten
Ending with 'k'
tank
ink
_.keys()
function returns an array of the property names of the JavaScript object and the _.values()
function returns an array of their values.<!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>
_.forIn()
function can be used to iterate over object properties.<!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>
_.add() Method
_.ceil() Method
_.divide() Method
_.floor() Method
_.max() Method
_.maxBy() Method
_.mean() Method
_.meanBy() Method
_.min() Method
_.minBy() Method
_.multiply() Method
_.round() Method
_.subtract() Method
_.sum() Method
_.sumBy() Method
Refernces : Lodash, Lodash Doc