Lodash

What is Lodash?

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.

Why use Lodash?

It will help you deal with all types of object and you will save you time by not coding generic functions. Your code will also be cleaner with LESS lines and it will work on all browsers. If you’re not currently using it, you should seriously think about it.

assign

_.assign 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.

var foo = { a: "a property" };
var bar = { b: 4, c: "an other property" }

var result = _.assign({ a: "an old property" }, foo, bar);
// result => { a: 'a property', b: 4, c: 'an other property' }

times

_.times receives as arguments the number of iterations and a function to execute n times and returns an array of the results. Very useful when creating dynamic test data.

function getRandomInteger() {
    return Math.round(Math.random() * 100);
}

var result = _.times(5, getRandomNumber);
// result => [64, 70, 29, 10, 23]


debounce

_.debounce will invoke a function after a certain amount of time since the last time it was invoked.

function validateEmail() {
    // Validate email here and show error message if not valid
}

var emailInput = document.getElementById("email-field");
emailInput.addEventListener("keyup", _.debounce(validateEmail, 500));

In this example, the function validateEmail will be invoked after 500ms so the error message won’t show instantly. The 500ms timer will reset on each keyup. This way, the user won’t see an error message until he stops typing.

find

Instead iterating through an array with a loop to find a specific object, we can simply use _.find. That’s nice, but this is not the only thing you can do with _.find. You can also find an object using multiple properties with a single line of code. Take a look!

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" });
// user -> { firstName: "John", lastName: "Doe", age: 28, gender: "male" }

var underAgeUser = _.find(users, function(user) {
    return user.age < 18;
});
// underAgeUser -> { firstName: "Jane", lastName: "Doe", age: 5, gender: "female" }

get and set

For this one I will cheat a little bit by presenting 2 functions that do almost the same thing. _.get will return a property value from an object and _.set will, well you guessed it, set a property with a value. Nothing special except that you can access a property with its path.
Let’s see an example.

var bar = { foo: { key: "foo" } };
_.set(bar, "foo.items[0]", "An item");
// bar => { foo: { key: "foo", items: ["An item"] } }
var name = _.get(bar, "name", "John Doe");
// name => John Doe

When using _.set, if the path doesn’t exist, it will be created. No more “Cannot set property ‘items’ of undefined” error. With _.get, if the path doesn’t exist, it will return undefined instead of an error. You can also specify a default value (third argument) if the path resolve to undefined.

deburr

This one is pretty simple. It removes all “combining diacritical marks”, so “é” becomes “e”.

_.deburr("déjà vu");
// -> deja vu
_.deburr("Juan José");
// -> Juan Jose

It’s a good habit to deburr text for a search function when there is internationalization and localization.

keyBy

_.keyBy is one of my favorites. It helps a lot when trying to get an object with a specific property. Let’s say we have 100 blog posts and we want to get the post with Id “34abc”. How can we achieve this? Let’s see!

var posts = [
    { id: "1abc", title: "First blog post", content: "..." },
    { id: "2abc", title: "Second blog post", content: "..." },
    // more blog posts
    { id: "34abc", title: "The blog post we want", content: "..." }
    // even more blog posts
];

posts = _.keyBy(posts, "id");

var post = posts["34abc"]
// post -> { id: "34abc", title: "The blog post we want", content: "..." }

Anytime a server returns an object collection as an array, this function can help you organize it. The second argument can also be a function.

reduce

_.reduce is a little bit like a filter function. The only difference is that you can choose the form of the returned object. If you don’t understand what I’m trying to say, it’s normal, there is an example for this reason.

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

// reducedUsers -> { 
//     28: [{ name: "Jane", age: 28 }], 
//     30: [{ name: "John", age: 30 }, { name: "Jack", age: 30 }] 
// }


Ouch! This is a tough one. So basically, we return a new object with users grouped by their age and only for user between 18 and 59. This helper function is one of the most used ones from Lodash. It is also part of ES6. I also want to point 2 common errors, don’t forget to return the result at the end of the function and don’t forget to specify the default value for the result as the third argument (here {}).

cloneDeep

After the hardest one, the easiest one. _.cloneDeep will clone an object. No kidding! The new object will also have a new address in memory so you won’t crush a property from the original object.

var original = { foo: "bar" };
var copy = original;
copy.foo = "new value";
// copy -> { foo: "new value" } Yeah!
// original -> { foo: "new value" } Oops!

var original = { foo: "bar" };
var copy = _.cloneDeep(original);
copy.foo = "new value";
// copy -> { foo: "new value" } Yeah!
// original -> { foo: "bar" } Yeah!

sortedUniq

With this one, all duplicated values won’t be returned. This is usually used for performance reasons, because it is specifically for the sorted arrays.

var sortedArray = [1, 1, 2, 3, 3, 3, 5, 8, 8];
var result = _.sortedUniq(sortedArray);
// -> [1, 2, 3, 5, 8]


This one is useful only if you deal with big array. If you want better performance you should sort your array and using functions that works better with sorted arrays. There are several other functions like this with Lodash. You can take a look at _.sortedIndex, _.sortedIndexBy, _.sortedIndexOf, _.sortedLastIndex, _.sortedLastIndexBy, _.sortedLastIndexOf, _.sortedUniq, _.sortedUniqBy.

Lodash provides a ton of helper functions to help you save time. The library is very light (69 KB), efficient, popular and loved (more than 18,000 starts on Github). It is updated very often and last time I looked at their GitHub page, there was 0 issue (Github page). If you are not currently using it it’s very easy to incorporate in an existing project. If you’re starting a new project soon, you should really think about using it. If you are here because you don’t now if you should use it or not … well, yes you should. I will conclude with an answer given by the author on Stackoverflow:

I created Lo-Dash to provide more consistent cross-environment iteration support for arrays, strings, objects, and arguments objects1. It has since become a superset of Underscore, providing more consistent API behavior, more features (like AMD support, deep clone, and deep merge), more thorough documentation and unit tests (tests which run in Node, Ringo, Rhino, Narwhal, PhantomJS, and browsers), better overall performance and optimizations for large arrays/object iteration, and more flexibility with custom builds and template pre-compilation utilities.

Official lodash.com


scr medium.com/