'Melhorando a manutenção da sua aplicação com 5 métodos Lodash'-cover.png
Adelly Lima

Adelly Lima

06 Dec 2021 5 min read

Improving the maintenance of your application with 5 Lodash methods

What is Lodash?

Lodash is a JavaScript library that provides many utility functions for tasks with arrays, numbers, objects and strings, using a functional programming paradigm. It is based on the old underscore.js library. If you've never heard of or used Lodash, here's a preview of it, full of examples that are very similar to common issues we face when developing a JavaScript project.

In this post I'll show you how Lodash can be great for iterating over arrays, objects and strings, manipulating and testing values. As Lodash has many built-in utility functions, coding in JavaScript is easier and cleaner. Instead of writing common functions over and over again, the task can be accomplished with just one line of code.

Next we'll understand how and when to use it, and apply it with practical examples.

How to use?

There are three paths to instal Lodash: via browser, npm or node.js.

In the browser:

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

Using npm:

$ npm i --save lodash

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

It's very simple to install and use, but, in practice, we're just going to use these utilitarian functions and identify that a native function is useful and clear to Lodash.

When to use Lodash or native javascript?

Lodash is a very good tool if you have more complex algorithms. It is the most legitimate and successful patronage of the code. Lodash can be very useful as it has many solutions that are not possible to implement in ES6 native. The patronage of coding helps a lot when collaborating between teams, mainly in a language that has many ways of making itself the same thing. Here are some examples of iterations on an object in ES6, with various approaches:

for (let key in obj) { console.log(obj[key]) }
for (let key of Object.keys(obj)) { console.log(obj[key]) }
Object.keys(obj).forEach((key) => { console.log(obj[key]) })

With Lodash, there is a unified _.forEach, for array and object:

_.forEach(obj, (value, key) => { console.log(value) })

For simple tasks, ES6 is recommended. And here you can see some simple examples of where using native functions might be easier:

_.map([1, 2, 3], (i) => i + 1)
_.reduce([1, 2, 3], (sum, i) => sum + i, 0)
_.filter([1, 2, 3], (i) => i > 1)
_.forEach([1, 2, 3], (i) => { console.log(i) })

// becomes
[1, 2, 3].map((i) => i + 1)
[1, 2, 3].reduce((sum, i) => sum + i, 0)
[1, 2, 3].filter((i) => i > 1)
[1, 2, 3].forEach((i) => { console.log(i) })

Once you understand how to install and when to use Lodash, you should practice using some useful functions. This is a way to start thinking in a more functional way.

5 useful examples of Lodash

xor/xorBy

The _.xor() method compares two lists and returns the difference between them, that is, it returns all elements that are different between the two lists. This is very useful for taking out a repeated element or adding an element that is unique in a list.

The example below shows a common scenario: imagine we have a list of products with id, name and color and we want to filter this list by products in red color. Let's use an empty list and the xor function to save the active filter:

 <script>
   let filtrosSelecionados = [];

   function toggleFilter(filter){
     filtrosSelecionados = _.xor(filtrosSelecionados, [filter]);
     console.log(filtrosSelecionados)
   }
 </script>

 <input type="checkbox" onClick={toggleFilter('red')}> red</input>

codepen

For more complex scenarios, such as comparing objects, it is recommended to use the .xorBy() method which, like .xor() , also returns the difference between lists. Except _.xorBy accepts a third parameter, which creates the criteria by which they are compared.

filter

The Lodash _.filter() method allows you to find multiple items of the same type in a collection. The return from this method is a list of results.

const productList = [
 { name: 'pencil', isRequired: true },
 { name: 'book', isRequired: true },
 { name: 'map', isRequired: false }
];

const requiredProducts = _.filter(productList, product => { return product.isRequired; });
console.log(requiredProducts);

// Output
// [{ name: 'pencil', isRequired: true }, { name: 'book', isRequired: true }]

codepen

find

The _.find() method iterates over the elements of a collection and returns the first element for which the predicate returns true.

const productList = [
 { name: 'backpack', amount: 1 },
 { name: 'paint', amount: 7 },
 { name: 'book', amount: 10 },
 { name: 'scissors', amount: 5 },
 { name: 'glue', amount: 3 },
 { name: 'pencil', amount: 8 },
 { name: 'eraser', amount: 3 },
];

const pencil = _.find(productList, {name: 'pencil'});
console.log(pencil);

const greaterAmount = _.find(productList, (product) => { return product.amount > 5 });
console.log(greaterAmount);

// Output
// {"name": "pencil", "amount": 8}
// {"name": "paint", "amount": 7}

codepen

orderBy

The _.orderBy() method allows ordering iterations to be sorted. If orders are not specified, all values are sorted in ascending order, otherwise the values are returned in an order of “desc” for descending or “asc” for ascending.

const productList = [
 { 'name': 'pencil',   'price': 20 },
 { 'name': 'book', 'price': 45 },
 { 'name': 'paint',   'price': 15 },
 { 'name': 'eraser', 'price': 8 }
];
const orderedProducts = _.orderBy(productList, ['price'], ['asc']);

console.log(orderedProducts);

// Output
//[{"name": "eraser", "price": 8}, {"name": "paint", "price": 15}, {"name": "pencil", "price": 20}, {"name": "book", "price": 45}]

codepen

debounce

The _.debounce method will invoke a function after a certain amount of time has passed since it was last invoked.

const search = (() => {
 console.log('Searching...');
})
const inputSearch = document.getElementById('search');

// search function debounced after 2 seconds
inputSearch.addEventListener('keyup', _.debounce(search, 2000));

codepen

In this example, the search function will be invoked after 2 seconds. That way we'll have time for the user to finish typing and then search. This function can be used for an ajax call for example.

Conclusion

I hope this post was a good incentive for you to start thinking about Lodash as a possibility for your project. We saw how to install it, practiced it and understood how and why to use this library. In the end, we realized that it can be a very useful tool when we know how to evaluate the appropriate scenarios, as it is a good way to save time and, above all, to get logical clarity, creating a clean and functional code.

Would you like to point out something interesting about this post? Contact us!

References