Skip to content

Instantly share code, notes, and snippets.

@serabakpak
Last active October 24, 2016 08:09
Show Gist options
  • Save serabakpak/28655ad3821aa66f744fd214be2bccfa to your computer and use it in GitHub Desktop.
Save serabakpak/28655ad3821aa66f744fd214be2bccfa to your computer and use it in GitHub Desktop.
Lodash Lightning Talk

Lodash

What it is

Lodash is a library of Javascript functions that provides clean, performant methods for manipulating objects, arrays, numbers, strings, etc.

Why it's awesome

Lodash makes JS more like Ruby because it gives you a whole bunch of commonly used helper utility functions (so you don't have to write your own!!)

Check out their docs!

How to get started

  1. To include in your project, you can download or use a CDN from here.

  2. Or, you can use npm

$ npm i -g npm
$ npm i --save lodash

Then don't forget to require

// Load the full build.
var _ = require('lodash');
// Load the core build.
var _ = require('lodash/core');

To test out Lodash code in the Node.js REPL, install n_:

$ npm install -g n_ 

Usage:

$ n_
n_ >

To exit:

$ .exit

Examples

// Example 1 - Get a random integer.

// JS utility method
function getRandomInt(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

getRandomInt(1, 20);

// The Lodash way
_.random(1, 20);
// Example 2

var array1 = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
var array2 = [3, 5, 7, 2];

_.shuffle(array1);
// => [ 2, 3, 4, 2, 4, 3, 3, 4, 1, 4 ]

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

_.without(array1, 2, 4);
// => [ 1, 3, 3, 3 ]

_.union(array1, array2);
// => [ 1, 2, 3, 4, 5, 7 ]
// Example 3

var people = [
	{name: 'Bob', age: 31 },
	{name: 'Sandra', age: 21 },
	{name: 'Adam', age: 15 },
	{name: 'Cat', age: 28 },
	{name: 'Christine', age: 28 },
	{name: 'Tim', age: 45 }
];

_.sortBy(people, 'name');
// => [ { name: 'Adam', age: 15 },
//  { name: 'Bob', age: 31 },
//  { name: 'Cat', age: 28 },
//  { name: 'Christine', age: 28 },
//  { name: 'Sandra', age: 21 },
//  { name: 'Tim', age: 45 } ]
  
_.chain(people).sortBy('age').max().value();
// => { name: 'Adam', age: 15 }

_.take(people, 2);
// => [ { name: 'Bob', age: 31 }, { name: 'Sandra', age: 21 } ]

_.takeRight(people, 3);
// => [ { name: 'Cat', age: 28 },
//  { name: 'Christine', age: 28 },
//  { name: 'Tim', age: 45 } ]
  
_.map(people, 'age')
// => [ 31, 21, 15, 28, 28, 45 ]
// Example 4

var bob = {
	name: 'Bob',
	age: 31,
	vehicle: 'scooter',
	fav_color: 'blue',
	kids: 6
};

_.omit(bob, ['vehicle', 'fav_color']);
// => { name: 'Bob', age: 31, kids: 6 }

_.pick(bob, ['vehicle', 'fav_color']);
// => { vehicle: 'scooter', fav_color: 'blue' }

Does ES6 Mean the End of Lodash?

Not according to this.

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment