A JavaScript utility library delivering consistency, modularity, performance, & extras.
<script src="lodash.js"></script>
$ npm i lodash # tip: i is an alias for install
// load the modern build
var _ = require('lodash');
// or a method category
var array = require('lodash/array');
// or just a method
var chunk = require('lodash/array/chunk');
In the browser:
Using npm:
In node.js:
_.funcName(argument, iteratee);
Basic structure in use:
var arr = [1,2,3];
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
What you're probably doing...
var arr = [1,2,3];
var sum = arr.reduce(function (prev, curr) {
return prev + curr;
}
What you may be doing...
var arr = [1,2,3];
var sum = _.sum(arr); // returns 6
var obj = {'a': 1, 'b': 2, 'c': 3};
var objSum = _.sum(obj); // returns 6
What you should be doing...
var matches = [];
pets.forEach(function (pet) {
if (pet.age === 6 && pet.color === 'brown') {
matches.push(pet);
}
});
What you're probably doing...
var pets = [
{name: 'Fluffy', age: 6, color: 'red'},
{name: 'Rex', age: 6, color: 'brown'},
{name: 'Spot', age: 6, color: 'brown'},
];
Some pets to work with...
var matches = _.where(pets, {age: 6, color: 'brown'});
What you should be doing...
for (var key in user) {
if (user[key]) {
user[key] = updated[key];
}
}
What you're probably doing...
var user = {name: 'Ryan', last: 'Dwyer', age: 25, eyes: 'brown'};
var updated = {name: 'Ryan', last: 'Dwyer', age: 26, eyes: 'blue'};
Some data to work with...
_.merge(user, updated);
What you should be doing...
function flatten(arr) {
var flattened = [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flattened = flattened.concat(flatten(arr[i]));
} else {
flattened.push(arr[i]);
}
}
return flattened;
}
function square (n) {
return n * n;
}
var flattened = flatten(arr);
flattened = flattened.map(square);
var sum = flattened.reduce(function (a, b) {
return a + b;
});
What you're probably doing...
var sum = _(arr) // creates a lodash object wrapper on arr
.flattenDeep // recursively flattens an array
.map(n => n * n) // squares each element
.sum(); // sums up the elements
var sum = _.chain(arr) // creates a lodash object wrapper on arr
.flattenDeep // recursively flattens an array
.map(n => n * n) // squares each element
.sum() // sums up the elements
.value() // required to unwrap the lodash object
Lodash
website: lodash.com/
documentation: lodash.com/docs
github: https://github.com/lodash/lodash
Egghead.io - Lodash
tutorial: egghead.io/lessons/core-javascript-introduction-to-lodash