I recently came upon a JS library called Lodash for a small app I am working on which supplies utility functions and readability of objects, arrays, string etc. There are more than 100 functions already added and split into 13 categories which simplify common problems. As hinted by the name, Lodash means, essentially, an underscore
Installation
With npm:
$ npm install lodash
And then import it at the top of your JavaScript file in which you would like to use it.
import _ from Lodash
Usage
Here are some of the functions that Lodash provides:
Map
Iterating over an array of an object with Lodash looks like:
const data = [
{
name: 'Bob',
age: '25',
},
{
name: 'Will',
age: '24',
},
{
name: 'Mary',
age: '26',
}
];
_.map(data, 'name');
// [ 'Bob', 'Will', 'Mary' ]
CloneDeep
This method recursively clones the whole object, so if any property of the resultant object changes, it will not change the original object as the references will also be new.
const users = [
{
name: 'Bob', age: '25', profile: { experience: 3 }
},
{
name: 'Will', age: '24', profile: { experience: 2 }
},
{
name: 'Mary', age: '26', profile: { experience: 4 }
}
];
const usersClone = _.cloneDeep(users);
usersClone[0].age = '27';
usersClone[0].age;
// 27
users[0].age;
// 25
Intersection
In this example you have two separate arrays with different ingredients in each and want to know which ones come up in both.
It would look like this in JS:
let array1 = ["pizza", "icecream", "salads"];
let array2 = ["burger","hotdog", "pasta"];
let commonResults = [];
for (let i = 0; I < array1.length; i++) [
if (array2.indexOf(array1[i]) !== -1) {
let indexPosition = array2.indexOf(array1[i]);
commonResults.push(array2[indexPosition]);
}
}
console.log(commonResults);
In lodash you can simply do:
console.log(_.intersection(array1, array2));
This is just a brief overview of Lodash and some of its utility functions. On the official site, you can read more documentation.
References
Top comments (0)