Lodash.js is a JavaScript utility library which provides a user access to a vast wealth of user-generated
functions.
Lodash helps the user to cut through the process of writing their own functions from scratch and instead delivers
packaged and working JavaScript to avoid unnecessary and extraneous work. Lodash has many categories that are
available
but is most utilized by developers to complete prompt work with Arrays, Collections, Objects, and Strings.
To get started with Lodash, you can either install using a script or an NPM install. For
practical purposes, we
will
just be using the script install here. Navigate to lodash.com and download the
full build. Then, add
a
script sourcing to this JavaScript file.
<script src="lodash.js"></script>
One of the easiest and most basic Lodash functions is _.capitalize. This function takes a string and
returns the
same
string, albeit with the first letter capitalized. This can be used to ensure proper capitalization on any variable
that
you wish to be displayed as a proper noun. Using the below code allows us to avoid what would otherwise be an
extensive
coding section using vanilla JavaScript.
const name = 'jackson'
console.log(_.capitalize(name))
// expected output = "Jackson"
Another useful Lodash tool is the _.findIndex function. This allows us to make quick use of searching
an array of objects to find the entry that matches multiple criteria. This function accepts 2 parameters: an array of objects to
search, and a collection of key and value pairs to check for. The Find Index function searches the array and returns
the index of the object that fulfills all the correct property values. If there is no object that fulfills all the
criteria, the function will return -1.
const personArray =[
{name: "John", age: 81, favoriteColor: "Orange"},
{name: "Paul", age: 79, favoriteColor: "Yellow"},
{name: "George", age: 78, favoriteColor: "Black"},
{name: "Ringo", age: 81, favoriteColor: "Blue"},
]
console.log(_.findIndex(personArray, {name: "Paul", age: 79, favoriteColor: "Yellow"})
//expected output = 1
Lodash has over 200 functions available for web development and I did not have time to research all of
them
but these were two that were presented as very introductory and tangible in their application. Check out the Lodash
site
and start digging into this useful tool for reducing coding headaches!