Lodash Library Usage Examples

Using Lodash library will make writing JS code so much easier. The good definition is: "Applicative programming is the pattern of defining a function that takes a function and then invokes that function for each element in a collection/list".

It has a very nice documentation.

Now, let's get to the actual work. Here is a list of the most commonly used functions for different data structures.

Common functions for collection

_.forEach - iterates over elements of the collection and invokes iteratee for each element.

_.forEach([1, 2], function(value) {
  console.log(value);
});
// => Logs `1` then `2`.
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed)

_.map - creates an array of values by running each element in the collection throught iteratee.

var users = [
  { 'user': 'barney' },
  { 'user': 'fred' }
];

_.map(users, 'user');
// => ['barney', 'fred']
function square(n) {
  return n * n;
}

_.map([4, 8], square);
// => [16, 64]

_.find - iterates over elements of the collection, returning the first element predicate returns truthy for.

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'

_.filter - returning new array of items based on a logical criteria.

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']

_.some - checks if the predicate returns truthy for any element of the collection. Iteration is stopped once the predicate returns truthy.

var users = [
  { 'user': 'barney', 'active': true },
  { 'user': 'fred',   'active': false }
];

_.some(users, { 'user': 'barney', 'active': false });
// => false

_.some(users, ['active', false]);
// => true

_.sortBy - allows sorting arrays by the specified value.

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
];

_.sortBy(users, ['user', 'age']);
// => [['barney', 36], ['fred', 40], ['fred', 48]]

Common functions for array

_.difference - creates an array of array values that are not included in the other given arrays. The order and references of result values are determined by the first array.

_.difference([2, 1], [2, 3]);
// => [1]

_.indexOf - gets the index at which the first occurrence of the value is found in array.

_.indexOf([1, 2, 1, 2], 2);
// => 1

_.uniq - creates a duplicate-free version of an array in which only the first occurrence of each element is kept.

_.uniq([2, 1, 2]);
// => [2, 1]

Check _.uniq_by too.

_.findIndex - similar to _.find except it returns the index of the first element.

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];
 
_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0

_.reverse - reverses array.

var array = [1, 2, 3];
 
_.reverse(array);
// => [3, 2, 1]

_.remove - removes all elements from array that predicate returns truthy for and returns an array of the removed elements.

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});
 
console.log(array);
// => [1, 3]
 
console.log(evens);
// => [2, 4]

_.slice - creates a slice of array from start up to, but not including, end.

var array = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];

_.slice(array, 1, 3)
// => ['Orange','Lemon']

Common functions for object

_.keys - creates an array of the own enumerable property names of the object.

function Foo() {
  this.a = 1;
  this.b = 2;
}

_.keys(new Foo);
// => ['a', 'b'] (iteration order is not guaranteed)

_.values - creates an array of the own enumerable string keyed property values of the object.

function Foo() {
  this.a = 1;
  this.b = 2;
}
 
_.values(new Foo);
// => [1, 2] (iteration order is not guaranteed)

_.pick - creates an object composed of the picked object properties.

var object = { 'a': 1, 'b': '2', 'c': 3 };
 
_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }

_.omit - creates an object composed of own and inherited enumerable property paths of objects that are not committed.

var object = { 'a': 1, 'b': '2', 'c': 3 };
 
_.omit(object, ['a', 'c']);
// => { 'b': '2' }

Common functions for string

_.capitalize - converts the first character of the string to upper case and the remaining to lower case.

_.capitalize('FRED');
// => 'Fred'

_.lowerCase - converts the string, as space separated words, to lower case.

_.lowerCase('fooBar');
// => 'foo bar'

_.includes - checks if the string contains substring.

_.includes('foobar', 'ob');
// → true

_.split - splits the string by a separator.

_.split('a-b-c', '-', 2);
// => ['a', 'b']

_.trim - removes leading and trailing whitespace or specified characters from the string.

_.trim('  abc  ');
// => 'abc'

Common math functions

_.sum - computes the sum of the values in array.

_.sum([4, 2, 8, 6]);
// => 20

Check _.sumBy too.

_.round - computes a number rounded to precision.

_.round(4.006);
// => 4
 
_.round(4.006, 2);
// => 4.01

_.random - produces a random number between the inclusive lower and upper bounds.

_.random(0, 5);
// => an integer between 0 and 5

_.max(array) - computes the maximum value of array. If the array is empty or falsey, undefined is returned.

_.max([4, 2, 8, 6]);
// => 8

Check _.min too.

_.mean(array) - computes the mean of the values in the array.

_.mean([4, 2, 8, 6]);
// => 5

You should also check out _.debounce, _.throttle and _.cloneDeep.

That's it! Thanks for reading!

If you want to know more how we can help you deal with writing JS code, subscribe to our newsletter!

References:
https://codehangar.io/common-lodash-functions/
https://vooban.com/en/send-english-newsletter-tips-articles-geek-stuff/10-lodash-functions-everyone-should-know/
http://ngninja.com/posts/powerful-lodash-functions-javascript
https://lodash.com/docs/