lodash

A JavaScript utility library delivering consistency, modularity, performance, & extras.

Example

_.assign({ 'a': 1 }, { 'b': 2 }, { 'c': 3 });
// → { 'a': 1, 'b': 2, 'c': 3 }

_.map([1, 2, 3], function(n) { return n * 3; });
// → [3, 6, 9]

Features

Download

Review the build differences & pick the one that’s right for you.

Installation

In a browser:

<script src="lodash.js"></script>

In an AMD loader:

require(['lodash'], function(_) {});

Using npm:

$ {sudo -H} npm i -g npm$ npm i --save lodash

In Node.js/io.js:

// load the modern build
var _ = require('lodash');

// or a method category
var array = require('lodash/array');

// or a method (great for smaller builds with browserify/webpack)
var chunk = require('lodash/array/chunk');

See the package source for more details.

Note: Don’t assign values to the special variable_” when in the REPL. Install n_ for a REPL that includes lodash by default.

Module formats

lodash is also available in a variety of other builds & module formats.

CDN copies are available on cdnjs & jsDelivr. Create custom builds with only the features you need. Looking for more functional usage? Try lodash-fp.

Dive in

Check out our changelog, roadmap, as well as community created podcasts, posts, & videos.

Support

Tested in Chrome 43-44, Firefox 38-39, IE 6-11, MS Edge, Safari 5-8, ChakraNode 0.12.2, Node.js 0.8.28, 0.10.40, 0.12.7, & 4.0.0, PhantomJS 1.9.8, RingoJS 0.11, & Rhino 1.7.6

Automated browser & CI test runs are available. Special thanks to Sauce Labs for providing automated browser testing.

Custom builds

Custom builds make it easy to create lightweight versions of lodash containing only the features you need. To top it off, we handle all function dependency & alias mapping for you. Review the build differences & pick the one that’s right for you.

Using Grunt? We also provide a Grunt plugin to build lodash as part of your Gruntfile.

The lodash command-line utility is available when lodash-cli is installed as a global package:

$ {sudo -H} npm i -g npm
$ {sudo -H} npm i -g lodash-cli
$ lodash -h

Note: Uninstall older versions before installing lodash-cli.

  • Compat builds, with support for old & new environments, are created using the compat modifier. (default)
lodash compat
  • Modern builds, tailored for newer environments with ES5/ES6 support, are created using the modern modifier.
lodash modern
  • Strict builds, with ES strict mode enabled, are created using the strict modifier.
lodash strict
  • Modularized builds, splitting lodash into modules, are created using the modularize modifier.
lodash modularize

Build commands:

  • Use the category command to pass comma separated categories of functions to include in the build. Valid categories are “array”, “chain”, “collection”, “date”, “function”, “lang”, “object”, “number”, “string”, & “utility”.
lodash category=collection,function
  • Use the exports command to pass comma separated names of ways to export the lodash function. Valid exports are “amd”, “commonjs”, “es”, “global”, “iojs”, “node”, “npm”, “none”, & “umd”.
lodash exports=amd,commonjs,iojs
  • Use the iife command to specify code to replace the IIFE that wraps lodash.
lodash iife="!function(window,undefined){%output%}(this)"
  • Use the include command to pass comma separated names of functions to include in the build.
lodash include=each,filter,map
  • Use the minus command to pass comma separated function/category names to remove from the build.
lodash modern minus=result,shuffle
  • Use the plus command to pass comma separated function/category names to add to the build.
lodash category=array plus=random,template
  • Use the template command to pass the file path pattern used to match template files to precompile. Note: Precompiled templates are assigned to the _.<span class="me1">templates</span> object.
lodash template="./*.jst"
  • Use the settings command to pass template settings used when precompiling templates.
lodash settings="{interpolate:/\{\{([\s\S]+?)\}\}/g}"
  • Use the moduleId command to specify the AMD module ID for lodash or the module ID used to include lodash in compiled templates. Use “none” as the module ID to create compiled templates without a dependency on lodash.
lodash moduleId=underscore

Notes:

  • All commands except compat & modern may be combined
  • The exports values “es” & “npm” may only be used in conjunction with the modularize command
  • The modularize command uses the first exports values as its module format, ignoring subsequent values.
  • Unless specified by -o or --output all files created are saved to the current working directory
  • Node.js 0.10.8-0.10.11 have bugs preventing minified builds

The following options are also supported:

-c, --stdout .......... Write output to standard output
-d, --development ..... Write only the non-minified development output
-h, --help ............ Display help information
-m, --source-map ...... Generate a source map using an optional source map URL
-o, --output .......... Write output to a given path/filename
-p, --production ...... Write only the minified production output
-s, --silent .......... Skip status updates normally logged to the console
-V, --version ......... Output current version of lodash

chunk source npm

_.chunk(array, [size=0])

Creates an array of elements split into groups the length of size. If collection can't be split evenly, the final chunk will be the remaining elements.

Arguments

  1. array (Array)

    The array to process.

  2. [size=0] (number)

    The length of each chunk.

Returns (Array)

Returns the new array containing chunks.

Example

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

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

compact source npm

_.compact(array)

Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are falsey.

Arguments

  1. array (Array)

    The array to compact.

Returns (Array)

Returns the new array of filtered values.

Example

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

difference source npm

_.difference(array, [values])

Creates an array of unique array values not included in the other provided arrays using SameValueZero for equality comparisons.

Arguments

  1. array (Array)

    The array to inspect.

  2. [values] (...Array)

    The values to exclude.

Returns (Array)

Returns the new array of filtered values.

Example

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

differenceBy source npm

_.differenceBy(array, [values], [iteratee=_.identity])

This method is like _.difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which uniqueness is computed. The iteratee is invoked with one argument: (value).

Arguments

  1. array (Array)

    The array to inspect.

  2. [values] (...Array)

    The values to exclude.

  3. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Array)

Returns the new array of filtered values.

Example

_.differenceBy([3.1, 2.2, 1.3], [4.4, 2.5], Math.floor);
// => [3.1, 1.3]

// using the `_.property` callback shorthand
_.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
// => [{ 'x': 2 }]

differenceWith source npm

_.differenceWith(array, [values], [comparator])

This method is like _.difference except that it accepts comparator which is invoked to compare elements of array to values. The comparator is invoked with two arguments: (arrVal, othVal).

Arguments

  1. array (Array)

    The array to inspect.

  2. [values] (...Array)

    The values to exclude.

  3. [comparator] (Function)

    The function invoked per element.

Returns (Array)

Returns the new array of filtered values.

Example

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];

_.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
// => [{ 'x': 2, 'y': 1 }]

drop source npm

_.drop(array, [n=1])

Creates a slice of array with n elements dropped from the beginning.

Arguments

  1. array (Array)

    The array to query.

  2. [n=1] (number)

    The number of elements to drop.

Returns (Array)

Returns the slice of array.

Example

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

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

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

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

dropRight source npm

_.dropRight(array, [n=1])

Creates a slice of array with n elements dropped from the end.

Arguments

  1. array (Array)

    The array to query.

  2. [n=1] (number)

    The number of elements to drop.

Returns (Array)

Returns the slice of array.

Example

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

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

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

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

dropRightWhile source npm

_.dropRightWhile(array, [predicate=_.identity])

Creates a slice of array excluding elements dropped from the end. Elements are dropped until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).

Arguments

  1. array (Array)

    The array to query.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the slice of array.

Example

var resolve = _.partial(_.map, _, 'user');

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

resolve( _.dropRightWhile(users, function(o) { return !o.active; }) );
// => ['barney']

// using the `_.matches` callback shorthand
resolve( _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }) );
// => ['barney', 'fred']

// using the `_.matchesProperty` callback shorthand
resolve( _.dropRightWhile(users, ['active', false]) );
// => ['barney']

// using the `_.property` callback shorthand
resolve( _.dropRightWhile(users, 'active') );
// => ['barney', 'fred', 'pebbles']

dropWhile source npm

_.dropWhile(array, [predicate=_.identity])

Creates a slice of array excluding elements dropped from the beginning. Elements are dropped until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).

Arguments

  1. array (Array)

    The array to query.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the slice of array.

Example

var resolve = _.partial(_.map, _, 'user');

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

resolve( _.dropWhile(users, function(o) { return !o.active; }) );
// => ['pebbles']

// using the `_.matches` callback shorthand
resolve( _.dropWhile(users, { 'user': 'barney', 'active': false }) );
// => ['fred', 'pebbles']

// using the `_.matchesProperty` callback shorthand
resolve( _.dropWhile(users, ['active', false]) );
// => ['pebbles']

// using the `_.property` callback shorthand
resolve( _.dropWhile(users, 'active') );
// => ['barney', 'fred', 'pebbles']

fill source npm

_.fill(array, value, [start=0], [end=array.length])

Fills elements of array with value from start up to, but not including, end.

Note: This method mutates array.

Arguments

  1. array (Array)

    The array to fill.

  2. value (*)

    The value to fill array with.

  3. [start=0] (number)

    The start position.

  4. [end=array.length] (number)

    The end position.

Returns (Array)

Returns array.

Example

var array = [1, 2, 3];

_.fill(array, 'a');
console.log(array);
// => ['a', 'a', 'a']

_.fill(Array(3), 2);
// => [2, 2, 2]

_.fill([4, 6, 8, 10], '*', 1, 3);
// => [4, '*', '*', 10]

findIndex source npm

_.findIndex(array, [predicate=_.identity])

This method is like _.find except that it returns the index of the first element predicate returns truthy for instead of the element itself.

Arguments

  1. array (Array)

    The array to search.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (number)

Returns the index of the found element, else -1.

Example

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

_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0

// using the `_.matches` callback shorthand
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1

// using the `_.matchesProperty` callback shorthand
_.findIndex(users, ['active', false]);
// => 0

// using the `_.property` callback shorthand
_.findIndex(users, 'active');
// => 2

findLastIndex source npm

_.findLastIndex(array, [predicate=_.identity])

This method is like _.findIndex except that it iterates over elements of collection from right to left.

Arguments

  1. array (Array)

    The array to search.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (number)

Returns the index of the found element, else -1.

Example

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

_.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
// => 2

// using the `_.matches` callback shorthand
_.findLastIndex(users, { 'user': 'barney', 'active': true });
// => 0

// using the `_.matchesProperty` callback shorthand
_.findLastIndex(users, ['active', false]);
// => 2

// using the `_.property` callback shorthand
_.findLastIndex(users, 'active');
// => 0

flatten source npm

_.flatten(array)

Flattens array a single level.

Arguments

  1. array (Array)

    The array to flatten.

Returns (Array)

Returns the new flattened array.

Example

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

flattenDeep source npm

_.flattenDeep(array)

This method is like _.flatten except that it recursively flattens array.

Arguments

  1. array (Array)

    The array to recursively flatten.

Returns (Array)

Returns the new flattened array.

Example

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

head first source npm

_.head(array)

Gets the first element of array.

Arguments

  1. array (Array)

    The array to query.

Returns (*)

Returns the first element of array.

Example

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

_.head([]);
// => undefined

indexOf source npm

_.indexOf(array, value, [fromIndex=0])

Gets the index at which the first occurrence of value is found in array using SameValueZero for equality comparisons. If fromIndex is negative, it's used as the offset from the end of array. If array is sorted providing true for fromIndex performs a faster binary search.

Arguments

  1. array (Array)

    The array to search.

  2. value (*)

    The value to search for.

  3. [fromIndex=0] (number)

    The index to search from.

Returns (number)

Returns the index of the matched value, else -1.

Example

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

// using `fromIndex`
_.indexOf([1, 2, 1, 2], 2, 2);
// => 3

initial source npm

_.initial(array)

Gets all but the last element of array.

Arguments

  1. array (Array)

    The array to query.

Returns (Array)

Returns the slice of array.

Example

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

intersection source npm

_.intersection([arrays])

Creates an array of unique values that are included in all of the provided arrays using SameValueZero for equality comparisons.

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

Returns (Array)

Returns the new array of shared values.

Example

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

intersectionBy source npm

_.intersectionBy([arrays], [iteratee=_.identity])

This method is like _.intersection except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. The iteratee is invoked with one argument: (value).

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Array)

Returns the new array of shared values.

Example

_.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
// => [2.1]

// using the `_.property` callback shorthand
_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }]

intersectionWith source npm

_.intersectionWith([arrays], [comparator])

This method is like _.intersection except that it accepts comparator which is invoked to compare elements of arrays. The comparator is invoked with two arguments: (arrVal, othVal).

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

  2. [comparator] (Function)

    The function invoked per element.

Returns (Array)

Returns the new array of shared values.

Example

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.intersectionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }]

last source npm

_.last(array)

Gets the last element of array.

Arguments

  1. array (Array)

    The array to query.

Returns (*)

Returns the last element of array.

Example

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

lastIndexOf source npm

_.lastIndexOf(array, value, [fromIndex=array.length-1])

This method is like _.indexOf except that it iterates over elements of array from right to left.

Arguments

  1. array (Array)

    The array to search.

  2. value (*)

    The value to search for.

  3. [fromIndex=array.length-1] (number)

    The index to search from.

Returns (number)

Returns the index of the matched value, else -1.

Example

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

// using `fromIndex`
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// => 1

prototype.reverse source npm

_.prototype.reverse()

Reverses array so that the first element becomes the last, the second element becomes the second to last, and so on.

Note: This method mutates array.

Returns (Array)

Returns array.

Example

var array = [1, 2, 3];

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

console.log(array);
// => [3, 2, 1]

pull source npm

_.pull(array, [values])

Removes all provided values from array using SameValueZero for equality comparisons.

Note: Unlike _.without, this method mutates array.

Arguments

  1. array (Array)

    The array to modify.

  2. [values] (...*)

    The values to remove.

Returns (Array)

Returns array.

Example

var array = [1, 2, 3, 1, 2, 3];

_.pull(array, 2, 3);
console.log(array);
// => [1, 1]

pullAll source npm

_.pullAll(array, values)

This method is like _.pull except that it accepts an array of values to remove.

Note: Unlike _.difference, this method mutates array.

Arguments

  1. array (Array)

    The array to modify.

  2. values (Array)

    The values to remove.

Returns (Array)

Returns array.

Example

var array = [1, 2, 3, 1, 2, 3];

_.pull(array, [2, 3]);
console.log(array);
// => [1, 1]

pullAllBy source npm

_.pullAllBy(array, values, [iteratee=_.identity])

This method is like _.pullAll except that it accepts iteratee which is invoked for each element of array and values to to generate the criterion by which uniqueness is computed. The iteratee is invoked with one argument: (value).

Note: Unlike _.differenceBy, this method mutates array.

Arguments

  1. array (Array)

    The array to modify.

  2. values (Array)

    The values to remove.

  3. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Array)

Returns array.

Example

var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];

_.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
console.log(array);
// => [{ 'x': 2 }]

pullAt source npm

_.pullAt(array, [indexes])

Removes elements from array corresponding to indexes and returns an array of removed elements.

Note: Unlike _.at, this method mutates array.

Arguments

  1. array (Array)

    The array to modify.

  2. [indexes] (...(number|number[])

    The indexes of elements to remove, specified individually or in arrays.

Returns (Array)

Returns the new array of removed elements.

Example

var array = [5, 10, 15, 20];
var evens = _.pullAt(array, 1, 3);

console.log(array);
// => [5, 15]

console.log(evens);
// => [10, 20]

remove source npm

_.remove(array, [predicate=_.identity])

Removes all elements from array that predicate returns truthy for and returns an array of the removed elements. The predicate is invoked with three arguments: (value, index, array).

Note: Unlike _.filter, this method mutates array.

Arguments

  1. array (Array)

    The array to modify.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the new array of removed elements.

Example

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 source npm

_.slice(array, [start=0], [end=array.length])

Creates a slice of array from start up to, but not including, end.

Note: This method is used instead of Array#slice to ensure dense arrays are returned.

Arguments

  1. array (Array)

    The array to slice.

  2. [start=0] (number)

    The start position.

  3. [end=array.length] (number)

    The end position.

Returns (Array)

Returns the slice of array.

sortedIndex source npm

_.sortedIndex(array, value)

Uses a binary search to determine the lowest index at which value should be inserted into array in order to maintain its sort order.

Arguments

  1. array (Array)

    The sorted array to inspect.

  2. value (*)

    The value to evaluate.

Returns (number)

Returns the index at which value should be inserted into array.

Example

_.sortedIndex([30, 50], 40);
// => 1

_.sortedIndex([4, 5], 4);
// => 0

sortedIndexBy source npm

_.sortedIndexBy(array, value, [iteratee=_.identity])

This method is like _.sortedIndex except that it accepts iteratee which is invoked for value and each element of array to compute their sort ranking. The iteratee is invoked with one argument: (value).

Arguments

  1. array (Array)

    The sorted array to inspect.

  2. value (*)

    The value to evaluate.

  3. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (number)

Returns the index at which value should be inserted into array.

Example

var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 };

_.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict));
// => 1

// using the `_.property` callback shorthand
_.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
// => 0

sortedIndexOf source npm

_.sortedIndexOf(array, value)

This method is like _.indexOf except that it performs a binary search on a sorted array.

Arguments

  1. array (Array)

    The array to search.

  2. value (*)

    The value to search for.

Returns (number)

Returns the index of the matched value, else -1.

Example

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

sortedLastIndex source npm

_.sortedLastIndex(array, value)

This method is like _.sortedIndex except that it returns the highest index at which value should be inserted into array in order to maintain its sort order.

Arguments

  1. array (Array)

    The sorted array to inspect.

  2. value (*)

    The value to evaluate.

Returns (number)

Returns the index at which value should be inserted into array.

Example

_.sortedLastIndex([4, 5], 4);
// => 1

sortedLastIndexBy source npm

_.sortedLastIndexBy(array, value, [iteratee=_.identity])

This method is like _.sortedLastIndex except that it accepts iteratee which is invoked for value and each element of array to compute their sort ranking. The iteratee is invoked with one argument: (value).

Arguments

  1. array (Array)

    The sorted array to inspect.

  2. value (*)

    The value to evaluate.

  3. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (number)

Returns the index at which value should be inserted into array.

Example

// using the `_.property` callback shorthand
_.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
// => 1

sortedLastIndexOf source npm

_.sortedLastIndexOf(array, value)

This method is like _.lastIndexOf except that it performs a binary search on a sorted array.

Arguments

  1. array (Array)

    The array to search.

  2. value (*)

    The value to search for.

Returns (number)

Returns the index of the matched value, else -1.

Example

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

sortedUniq source npm

_.sortedUniq(array)

This method is like _.uniq except that it's designed and optimized for sorted arrays.

Arguments

  1. array (Array)

    The array to inspect.

Returns (Array)

Returns the new duplicate free array.

Example

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

sortedUniqBy source npm

_.sortedUniqBy(array, [iteratee])

This method is like _.uniqBy except that it's designed and optimized for sorted arrays.

Arguments

  1. array (Array)

    The array to inspect.

  2. [iteratee] (Function)

    The function invoked per element.

Returns (Array)

Returns the new duplicate free array.

Example

_.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
// => [1.1, 2.2]

tail source npm

_.tail(array)

Gets all but the first element of array.

Arguments

  1. array (Array)

    The array to query.

Returns (Array)

Returns the slice of array.

Example

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

take source npm

_.take(array, [n=1])

Creates a slice of array with n elements taken from the beginning.

Arguments

  1. array (Array)

    The array to query.

  2. [n=1] (number)

    The number of elements to take.

Returns (Array)

Returns the slice of array.

Example

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

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

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

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

takeRight source npm

_.takeRight(array, [n=1])

Creates a slice of array with n elements taken from the end.

Arguments

  1. array (Array)

    The array to query.

  2. [n=1] (number)

    The number of elements to take.

Returns (Array)

Returns the slice of array.

Example

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

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

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

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

takeRightWhile source npm

_.takeRightWhile(array, [predicate=_.identity])

Creates a slice of array with elements taken from the end. Elements are taken until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).

Arguments

  1. array (Array)

    The array to query.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the slice of array.

Example

var resolve = _.partial(_.map, _, 'user');

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

resolve( _.takeRightWhile(users, function(o) { return !o.active; }) );
// => ['fred', 'pebbles']

// using the `_.matches` callback shorthand
resolve( _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }) );
// => ['pebbles']

// using the `_.matchesProperty` callback shorthand
resolve( _.takeRightWhile(users, ['active', false]) );
// => ['fred', 'pebbles']

// using the `_.property` callback shorthand
resolve( _.takeRightWhile(users, 'active') );
// => []

takeWhile source npm

_.takeWhile(array, [predicate=_.identity])

Creates a slice of array with elements taken from the beginning. Elements are taken until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).

Arguments

  1. array (Array)

    The array to query.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the slice of array.

Example

var resolve = _.partial(_.map, _, 'user');

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

resolve( _.takeWhile(users, function(o) { return !o.active; }) );
// => ['barney', 'fred']

// using the `_.matches` callback shorthand
resolve( _.takeWhile(users, { 'user': 'barney', 'active': false }) );
// => ['barney']

// using the `_.matchesProperty` callback shorthand
resolve( _.takeWhile(users, ['active', false]) );
// => ['barney', 'fred']

// using the `_.property` callback shorthand
resolve( _.takeWhile(users, 'active') );
// => []

union source npm

_.union([arrays])

Creates an array of unique values, in order, from all of the provided arrays using SameValueZero for equality comparisons.

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

Returns (Array)

Returns the new array of combined values.

Example

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

unionBy source npm

_.unionBy([arrays], [iteratee=_.identity])

This method is like _.union except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. The iteratee is invoked with one argument: (value).

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Array)

Returns the new array of combined values.

Example

_.unionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
// => [2.1, 1.2, 4.3]

// using the `_.property` callback shorthand
_.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]

unionWith source npm

_.unionWith([arrays], [comparator])

This method is like _.union except that it accepts comparator which is invoked to compare elements of arrays. The comparator is invoked with two arguments: (arrVal, othVal).

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

  2. [comparator] (Function)

    The function invoked per element.

Returns (Array)

Returns the new array of combined values.

Example

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.unionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]

uniq source npm

_.uniq(array)

Creates a duplicate-free version of an array, using SameValueZero for equality comparisons, in which only the first occurrence of each element is kept.

Arguments

  1. array (Array)

    The array to inspect.

Returns (Array)

Returns the new duplicate free array.

Example

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

uniqBy source npm

_.uniqBy(array, [iteratee=_.identity])

This method is like _.uniq except that it accepts iteratee which is invoked for each element in array to generate the criterion by which uniqueness is computed. The iteratee is invoked with one argument: (value).

Arguments

  1. array (Array)

    The array to inspect.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Array)

Returns the new duplicate free array.

Example

_.uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]

// using the `_.property` callback shorthand
_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]

uniqWith source npm

_.uniqWith(array, [comparator])

This method is like _.uniq except that it accepts comparator which is invoked to compare elements of array. The comparator is invoked with two arguments: (arrVal, othVal).

Arguments

  1. array (Array)

    The array to inspect.

  2. [comparator] (Function)

    The function invoked per element.

Returns (Array)

Returns the new duplicate free array.

Example

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 },  { 'x': 1, 'y': 2 }];

_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

unzip source npm

_.unzip(array)

This method is like _.zip except that it accepts an array of grouped elements and creates an array regrouping the elements to their pre-zip configuration.

Arguments

  1. array (Array)

    The array of grouped elements to process.

Returns (Array)

Returns the new array of regrouped elements.

Example

var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
// => [['fred', 30, true], ['barney', 40, false]]

_.unzip(zipped);
// => [['fred', 'barney'], [30, 40], [true, false]]

unzipWith source npm

_.unzipWith(array, [iteratee=_.identity])

This method is like _.unzip except that it accepts iteratee to specify how regrouped values should be combined. The iteratee is invoked with four arguments: (accumulator, value, index, group). The first element of each group is used as the initial accumulator value.

Arguments

  1. array (Array)

    The array of grouped elements to process.

  2. [iteratee=_.identity] (Function)

    The function to combine regrouped values.

Returns (Array)

Returns the new array of regrouped elements.

Example

var zipped = _.zip([1, 2], [10, 20], [100, 200]);
// => [[1, 10, 100], [2, 20, 200]]

_.unzipWith(zipped, _.add);
// => [3, 30, 300]

without source npm

_.without(array, [values])

Creates an array excluding all provided values using SameValueZero for equality comparisons.

Arguments

  1. array (Array)

    The array to filter.

  2. [values] (...*)

    The values to exclude.

Returns (Array)

Returns the new array of filtered values.

Example

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

xor source npm

_.xor([arrays])

Creates an array of unique values that is the symmetric difference of the provided arrays.

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

Returns (Array)

Returns the new array of values.

Example

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

xorBy source npm

_.xorBy([arrays], [iteratee=_.identity])

This method is like _.xor except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. The iteratee is invoked with one argument: (value).

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Array)

Returns the new array of values.

Example

_.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor);
// => [1.2, 4.3]

// using the `_.property` callback shorthand
_.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 2 }]

xorWith source npm

_.xorWith([arrays], [comparator])

This method is like _.xor except that it accepts comparator which is invoked to compare elements of arrays. The comparator is invoked with two arguments: (arrVal, othVal).

Arguments

  1. [arrays] (...Array)

    The arrays to inspect.

  2. [comparator] (Function)

    The function invoked per element.

Returns (Array)

Returns the new array of values.

Example

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.xorWith(objects, others, _.isEqual);
// => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]

zip source npm

_.zip([arrays])

Creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.

Arguments

  1. [arrays] (...Array)

    The arrays to process.

Returns (Array)

Returns the new array of grouped elements.

Example

_.zip(['fred', 'barney'], [30, 40], [true, false]);
// => [['fred', 30, true], ['barney', 40, false]]

zipObject source npm

_.zipObject(props, [values=[]])

The inverse of _.pairs; this method returns an object composed from arrays of property names and values. Provide either a single two dimensional array, e.g. [[key1, value1], [key2, value2]] or two arrays, one of property names and one of corresponding values.

Arguments

  1. props (Array)

    The property names.

  2. [values=[]] (Array)

    The property values.

Returns (Object)

Returns the new object.

Example

_.zipObject([['fred', 30], ['barney', 40]]);
// => { 'fred': 30, 'barney': 40 }

_.zipObject(['fred', 'barney'], [30, 40]);
// => { 'fred': 30, 'barney': 40 }

zipWith source npm

_.zipWith([arrays], [iteratee=_.identity])

This method is like _.zip except that it accepts iteratee to specify how grouped values should be combined. The iteratee is invoked with four arguments: (accumulator, value, index, group). The first element of each group is used as the initial accumulator value.

Arguments

  1. [arrays] (...Array)

    The arrays to process.

  2. [iteratee=_.identity] (Function)

    The function to combine grouped values.

Returns (Array)

Returns the new array of grouped elements.

Example

_.zipWith([1, 2], [10, 20], [100, 200], _.add);
// => [111, 222]

_ source

_(value)

Creates a lodash object which wraps value to enable implicit method chaining. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primitive value will automatically end the chain sequence and return the unwrapped value. Otherwise, the value must be unwrapped with _#value.

Explicit chaining, which must be unwrapped with _#value in all cases, may be enabled using _.chain.

The execution of chained methods is lazy, that is, execution is deferred until _#value is implicitly or explicitly called.

Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion is an optimization strategy which merge iteratee calls; this can help to avoid the creation of intermediate data structures and greatly reduce the number of iteratee executions. Sections of a chain sequence may qualify for shortcut fusion if the section is applied to an array of at least two hundred elements and any iteratees or predicates accept only one argument. The heuristic for whether a section qualifies for shortcut fusion is subject to change.

Chaining is supported in custom builds as long as the _#value method is directly or indirectly included in the build.

In addition to lodash methods, wrappers have Array and String methods.

The wrapper Array methods are:
concat, join, pop, push, shift, sort, splice, and unshift

The wrapper String methods are:
replace and split

The wrapper methods that support shortcut fusion are:
compact, drop, dropRight, dropWhile, filter, find, findLast, head, initial, last, map, reject, reverse, slice, tail, take, takeRight, takeRightWhile, takeWhile, and toArray

The chainable wrapper methods are:
after, ary, assign, assignIn, assignInWith, assignWith, at, before, bind, bindAll, bindKey, chain, chunk, commit, compact, concat, conforms, conj, constant, countBy, create, curry, debounce, defaults, defaultsDeep, defer, delay, difference, differenceBy, differenceWith, disj, drop, dropRight, dropRightWhile, dropWhile, fill, filter, flatten, flattenDeep, flip, flow, flowRight, forEach, forEachRight, forIn, forInRight, forOwn, forOwnRight, functions, functionsIn, groupBy, initial, intersection, intersectionBy, intersectionWith, invert,invoke,iteratee,keyBy,keys,keysIn,map,mapKeys,mapValues,matches,matchesProperty,memoize,merge,mergeWith,method,methodOf,mixin,modArgs,modArgsSet', negate, nthArg, omit, omitBy, once, pairs, pairsIn, partial, partialRight, partition, pick, pickBy, plant, property, propertyOf, pull, pullAll, pullAllBy, pullAt, push, range, rearg, reject, remove, rest, reverse, sampleSize, set, setWith, shuffle, slice, sort, sortBy, sortByOrder, splice, spread, tail, take, takeRight, takeRightWhile, takeWhile, tap, throttle, thru, times, toArray, toPath, toPlainObject, transform, unary, union, unionBy, unionWith, uniq, uniqBy, uniqWith, unset, unshift, unzip, unzipWith, values, valuesIn, without, wrap, xor, xorBy, xorWith, zip, zipObject, and zipWith

The wrapper methods that are not chainable by default are:
add, attempt, camelCase, capitalize, ceil, clamp, clone, cloneDeep, cloneDeepWith, cloneWith, deburr, endsWith, eq, escape, escapeRegExp, every, find, findIndex, findKey, findLast, findLastIndex, findLastKey, floor, get, gt, gte, has, hasIn, head, identity, includes, indexOf, inRange, isArguments, isArray, isArrayLike, isArrayLikeObject, isBoolean, isDate, isElement, isEmpty, isEqual, isEqualWith, isError, isFinite, isFunction, isInteger, isLength, isMatch, isMatchWith, isNaN, isNative, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isRegExp, isSafeInteger, isString, isUndefined, isTypedArray, join, kebabCase, last, lastIndexOf, lowerCase, lowerFirst, lt, lte, max, maxBy, min, minBy, noConflict, noop, now, pad, padLeft, padRight, parseInt, pop, random, reduce, reduceRight, repeat, result, round, runInContext, sample, shift, size, snakeCase, some, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, startCase, startsWith, sum, sumBy, template, toLower, toInteger, toLength, toNumber, toSafeInteger, toString,toUpper,trim,trimLeft,trimRight,truncate,unescape,uniqueId,upperCase,upperFirst,value, andwords`

Arguments

  1. value (*)

    The value to wrap in a lodash instance.

Returns (Object)

Returns the new lodash wrapper instance.

Example

function square(n) {
  return n * n;
}

var wrapped = _([1, 2, 3]);

// returns an unwrapped value
wrapped.reduce(_.add);
// => 6

// returns a wrapped value
var squares = wrapped.map(square);

_.isArray(squares);
// => false

_.isArray(squares.value());
// => true

chain source

_.chain(value)

Creates a lodash object that wraps value with explicit method chaining enabled. The result of such method chaining must be unwrapped with _#value.

Arguments

  1. value (*)

    The value to wrap.

Returns (Object)

Returns the new lodash wrapper instance.

Example

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

var youngest = _
  .chain(users)
  .sortBy('age')
  .map(function(o) {
    return o.user + ' is ' + o.age;
  })
  .head()
  .value();
// => 'pebbles is 1'

prototype.chain source

_.prototype.chain()

Enables explicit method chaining on the wrapper object.

Returns (Object)

Returns the new lodash wrapper instance.

Example

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

// without explicit chaining
_(users).head();
// => { 'user': 'barney', 'age': 36 }

// with explicit chaining
_(users)
  .chain()
  .head()
  .pick('user')
  .value();
// => { 'user': 'barney' }

prototype.commit source

_.prototype.commit()

Executes the chained sequence and returns the wrapped result.

Returns (Object)

Returns the new lodash wrapper instance.

Example

var array = [1, 2];
var wrapped = _(array).push(3);

console.log(array);
// => [1, 2]

wrapped = wrapped.commit();
console.log(array);
// => [1, 2, 3]

wrapped.last();
// => 3

console.log(array);
// => [1, 2, 3]

prototype.concat source

_.prototype.concat([values])

Creates a new array joining a wrapped array with any additional arrays and/or values.

Arguments

  1. [values] (...*)

    The values to concatenate.

Returns (Array)

Returns the new concatenated array.

Example

var array = [1];
var wrapped = _(array).concat(2, [3], [[4]]);

console.log(wrapped.value());
// => [1, 2, 3, [4]]

console.log(array);
// => [1]

prototype.next source

_.prototype.next()

Gets the next value on a wrapped object following the iterator protocol.

Returns (Object)

Returns the next iterator value.

Example

var wrapped = _([1, 2]);

wrapped.next();
// => { 'done': false, 'value': 1 }

wrapped.next();
// => { 'done': false, 'value': 2 }

wrapped.next();
// => { 'done': true, 'value': undefined }

prototype.plant source

_.prototype.plant(value)

Creates a clone of the chained sequence planting value as the wrapped value.

Arguments

  1. value (*)

    The value to plant.

Returns (Object)

Returns the new lodash wrapper instance.

Example

function square(n) {
  return n * n;
}

var wrapped = _([1, 2]).map(square);
var other = wrapped.plant([3, 4]);

other.value();
// => [9, 16]

wrapped.value();
// => [1, 4]

prototype.Symbol.iterator source

_.prototype.Symbol.iterator()

Enables the wrapper to be iterable.

Returns (Object)

Returns the wrapper object.

Example

var wrapped = _([1, 2]);

wrapped[Symbol.iterator]() === wrapped;
// => true

Array.from(wrapped);
// => [1, 2]

prototype.value run, toJSON, valueOf source

_.prototype.value()

Executes the chained sequence to extract the unwrapped value.

Returns (*)

Returns the resolved unwrapped value.

Example

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

tap source

_.tap(value, interceptor)

This method invokes interceptor and returns value. The interceptor is invoked with one argument; (value). The purpose of this method is to "tap into" a method chain in order to perform operations on intermediate results within the chain.

Arguments

  1. value (*)

    The value to provide to interceptor.

  2. interceptor (Function)

    The function to invoke.

Returns (*)

Returns value.

Example

_([1, 2, 3])
 .tap(function(array) {
   array.pop();
 })
 .reverse()
 .value();
// => [2, 1]

thru source

_.thru(value, interceptor)

This method is like _.tap except that it returns the result of interceptor.

Arguments

  1. value (*)

    The value to provide to interceptor.

  2. interceptor (Function)

    The function to invoke.

Returns (*)

Returns the result of interceptor.

Example

_('  abc  ')
 .chain()
 .trim()
 .thru(function(value) {
   return [value];
 })
 .value();
// => ['abc']

countBy source npm

_.countBy(collection, [iteratee=_.identity])

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the number of times the key was returned by iteratee. The iteratee is invoked with one argument: (value).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Object)

Returns the composed aggregate object.

Example

_.countBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': 1, '6': 2 }

_.countBy(['one', 'two', 'three'], 'length');
// => { '3': 2, '5': 1 }

every source npm

_.every(collection, [predicate=_.identity])

Checks if predicate returns truthy for all elements of collection. Iteration is stopped once predicate returns falsey. The predicate is invoked with three arguments: (value, index|key, collection).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (boolean)

Returns true if all elements pass the predicate check, else false.

Example

_.every([true, 1, null, 'yes'], Boolean);
// => false

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

// using the `_.matches` callback shorthand
_.every(users, { 'user': 'barney', 'active': false });
// => false

// using the `_.matchesProperty` callback shorthand
_.every(users, ['active', false]);
// => true

// using the `_.property` callback shorthand
_.every(users, 'active');
// => false

filter source npm

_.filter(collection, [predicate=_.identity])

Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments:
(value, index|key, collection).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the new filtered array.

Example

var resolve = _.partial(_.map, _, 'user');

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

resolve( _.filter(users, function(o) { return !o.active; }) );
// => ['fred']

// using the `_.matches` callback shorthand
resolve( _.filter(users, { 'age': 36, 'active': true }) );
// => ['barney']

// using the `_.matchesProperty` callback shorthand
resolve( _.filter(users, ['active', false]) );
// => ['fred']

// using the `_.property` callback shorthand
resolve( _.filter(users, 'active') );
// => ['barney']

find source npm

_.find(collection, [predicate=_.identity])

Iterates over elements of collection, returning the first element predicate returns truthy for. The predicate is invoked with three arguments:
(value, index|key, collection).

Arguments

  1. collection (Array|Object)

    The collection to search.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (*)

Returns the matched element, else undefined.

Example

var resolve = _.partial(_.result, _, 'user');

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

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

// using the `_.matches` callback shorthand
resolve( _.find(users, { 'age': 1, 'active': true }) );
// => 'pebbles'

// using the `_.matchesProperty` callback shorthand
resolve( _.find(users, ['active', false]) );
// => 'fred'

// using the `_.property` callback shorthand
resolve( _.find(users, 'active') );
// => 'barney'

findLast source npm

_.findLast(collection, [predicate=_.identity])

This method is like _.find except that it iterates over elements of collection from right to left.

Arguments

  1. collection (Array|Object)

    The collection to search.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (*)

Returns the matched element, else undefined.

Example

_.findLast([1, 2, 3, 4], function(n) {
  return n % 2 == 1;
});
// => 3

forEach each source npm

_.forEach(collection, [iteratee=_.identity])

Iterates over elements of collection invoking iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

Note: As with other "Collections" methods, objects with a "length" property are iterated like arrays. To avoid this behavior use _.forIn or _.forOwn for object iteration.

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

Returns (Array|Object)

Returns collection.

Example

_([1, 2]).forEach(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)

forEachRight eachRight source npm

_.forEachRight(collection, [iteratee=_.identity])

This method is like _.forEach except that it iterates over elements of collection from right to left.

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

Returns (Array|Object)

Returns collection.

Example

_.forEachRight([1, 2], function(value) {
  console.log(value);
});
// => logs `2` then `1`

groupBy source npm

_.groupBy(collection, [iteratee=_.identity])

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is an array of the elements responsible for generating the key. The iteratee is invoked with one argument: (value).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Object)

Returns the composed aggregate object.

Example

_.groupBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': [4.2], '6': [6.1, 6.3] }

// using the `_.property` callback shorthand
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }

includes source npm

_.includes(collection, target, [fromIndex=0])

Checks if target is in collection using SameValueZero for equality comparisons. If fromIndex is negative, it's used as the offset from the end of collection.

Arguments

  1. collection (Array|Object|string)

    The collection to search.

  2. target (*)

    The value to search for.

  3. [fromIndex=0] (number)

    The index to search from.

Returns (boolean)

Returns true if target is found, else false.

Example

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

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

_.includes({ 'user': 'fred', 'age': 40 }, 'fred');
// => true

_.includes('pebbles', 'eb');
// => true

invoke source npm

_.invoke(collection, path, [args])

Invokes the method at path of each element in collection, returning an array of the results of each invoked method. Any additional arguments are provided to each invoked method. If methodName is a function it's invoked for, and this bound to, each element in collection.

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. path (Array|Function|string)

    The path of the method to invoke or the function invoked per iteration.

  3. [args] (...*)

    The arguments to invoke the method with.

Returns (Array)

Returns the array of results.

Example

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
// => [[1, 5, 7], [1, 2, 3]]

_.invoke([123, 456], String.prototype.split, '');
// => [['1', '2', '3'], ['4', '5', '6']]

keyBy source npm

_.keyBy(collection, [iteratee=_.identity])

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the last element responsible for generating the key. The iteratee is invoked with one argument: (value).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (Object)

Returns the composed aggregate object.

Example

var keyData = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'right', 'code': 100 }
];

_.keyBy(keyData, 'dir');
// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }

_.keyBy(keyData, function(o) {
  return String.fromCharCode(o.code);
});
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }

map source npm

_.map(collection, [iteratee=_.identity])

Creates an array of values by running each element in collection through iteratee. The iteratee is invoked with three arguments:
(value, index|key, collection).

Many lodash methods are guarded to work as iteratees for methods like _.every, _.filter, _.map, _.mapValues, _.reject, and _.some.

The guarded methods are:
ary, callback, curry, curryRight, drop, dropRight, every, fill, invert, parseInt, random, range, slice, some, sortBy, take, takeRight, template, trim, trimLeft, trimRight, uniq, and words

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the new mapped array.

Example

function square(n) {
  return n * n;
}

_.map([1, 2], square);
// => [3, 6]

_.map({ 'a': 1, 'b': 2 }, square);
// => [3, 6] (iteration order is not guaranteed)

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

// using the `_.property` callback shorthand
_.map(users, 'user');
// => ['barney', 'fred']

partition source npm

_.partition(collection, [predicate=_.identity])

Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, while the second of which contains elements predicate returns falsey for. The predicate is invoked with three arguments: (value, index|key, collection).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the array of grouped elements.

Example

var resolve = function(result) {
  return _.map(result, function(array) { return _.map(array, 'user'); });
};

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

resolve( _.partition(users, function(o) { return o.active; }) );
// => [['fred'], ['barney', 'pebbles']]

// using the `_.matches` callback shorthand
resolve( _.partition(users, { 'age': 1, 'active': false }) );
// => [['pebbles'], ['barney', 'fred']]

// using the `_.matchesProperty` callback shorthand
resolve( _.partition(users, ['active', false]) );
// => [['barney', 'pebbles'], ['fred']]

// using the `_.property` callback shorthand
resolve( _.partition(users, 'active') );
// => [['fred'], ['barney', 'pebbles']]

reduce source npm

_.reduce(collection, [iteratee=_.identity], [accumulator])

Reduces collection to a value which is the accumulated result of running each element in collection through iteratee, where each successive invocation is supplied the return value of the previous. If accumulator is not provided the first element of collection is used as the initial value. The iteratee is invoked with four arguments:
(accumulator, value, index|key, collection).

Many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform.

The guarded methods are:
assign, defaults, defaultsDeep, includes, merge, sortBy, and sortByOrder

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

  3. [accumulator] (*)

    The initial value.

Returns (*)

Returns the accumulated value.

Example

_.reduce([1, 2], function(sum, n) {
  return sum + n;
});
// => 3

_.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
  return result;
}, {});
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)

reduceRight source npm

_.reduceRight(collection, [iteratee=_.identity], [accumulator])

This method is like _.reduce except that it iterates over elements of collection from right to left.

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

  3. [accumulator] (*)

    The initial value.

Returns (*)

Returns the accumulated value.

Example

var array = [[0, 1], [2, 3], [4, 5]];

_.reduceRight(array, function(flattened, other) {
  return flattened.concat(other);
}, []);
// => [4, 5, 2, 3, 0, 1]

reject source npm

_.reject(collection, [predicate=_.identity])

The opposite of _.filter; this method returns the elements of collection that predicate does not return truthy for.

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Array)

Returns the new filtered array.

Example

var resolve = _.partial(_.map, _, 'user');

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

resolve( _.reject(users, function(o) { return !o.active; }) );
// => ['fred']

// using the `_.matches` callback shorthand
resolve( _.reject(users, { 'age': 40, 'active': true }) );
// => ['barney']

// using the `_.matchesProperty` callback shorthand
resolve( _.reject(users, ['active', false]) );
// => ['fred']

// using the `_.property` callback shorthand
resolve( _.reject(users, 'active') );
// => ['barney']

sample source npm

_.sample(collection)

Gets a random element from collection.

Arguments

  1. collection (Array|Object)

    The collection to sample.

Returns (*)

Returns the random element.

Example

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

sampleSize source npm

_.sampleSize(collection, [n=0])

Gets n random elements from collection.

Arguments

  1. collection (Array|Object)

    The collection to sample.

  2. [n=0] (number)

    The number of elements to sample.

Returns (Array)

Returns the random elements.

Example

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

shuffle source npm

_.shuffle(collection)

Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.

Arguments

  1. collection (Array|Object)

    The collection to shuffle.

Returns (Array)

Returns the new shuffled array.

Example

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

size source npm

_.size(collection)

Gets the size of collection by returning its length for array-like values or the number of own enumerable properties for objects.

Arguments

  1. collection (Array|Object)

    The collection to inspect.

Returns (number)

Returns the collection size.

Example

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

_.size({ 'a': 1, 'b': 2 });
// => 2

_.size('pebbles');
// => 7

some source npm

_.some(collection, [predicate=_.identity])

Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy. The predicate is invoked with three arguments: (value, index|key, collection).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (boolean)

Returns true if any element passes the predicate check, else false.

Example

_.some([null, 0, 'yes', false], Boolean);
// => true

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

// using the `_.matches` callback shorthand
_.some(users, { 'user': 'barney', 'active': false });
// => false

// using the `_.matchesProperty` callback shorthand
_.some(users, ['active', false]);
// => true

// using the `_.property` callback shorthand
_.some(users, 'active');
// => true

sortBy source npm

_.sortBy(collection, [iteratees=[_.identity]])

Creates an array of elements, sorted in ascending order by the results of running each element in a collection through each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratees=[_.identity]] (...(Function|Function[]|Object|Object[]|string|string[])

    The iteratees to sort by, specified individually or in arrays.

Returns (Array)

Returns the new sorted array.

Example

var resolve = _.partial(_.map, _, _.values);

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

resolve( _.sortBy(users, function(o) { return o.user; }) );
// => // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]

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

resolve( _.sortBy(users, 'user', function(o) {
  return Math.floor(o.age / 10);
}) );
// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]

sortByOrder source npm

_.sortByOrder(collection, [iteratees=[_.identity]], [orders])

This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, a value is sorted in ascending order if its corresponding order is "asc", and descending if "desc".

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratees=[_.identity]] (Function[]|Object[]|string[])

    The iteratees to sort by.

  3. [orders] (string[])

    The sort orders of iteratees.

Returns (Array)

Returns the new sorted array.

Example

var resolve = _.partial(_.map, _, _.values);

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

// sort by `user` in ascending order and by `age` in descending order
resolve( _.sortByOrder(users, ['user', 'age'], ['asc', 'desc']) );
// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]

now source npm

_.now()

Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).

Returns (number)

Returns the timestamp.

Example

_.defer(function(stamp) {
  console.log(_.now() - stamp);
}, _.now());
// => logs the number of milliseconds it took for the deferred function to be invoked

after source npm

_.after(n, func)

The opposite of _.before; this method creates a function that invokes func once it's called n or more times.

Arguments

  1. n (number)

    The number of calls before func is invoked.

  2. func (Function)

    The function to restrict.

Returns (Function)

Returns the new restricted function.

Example

var saves = ['profile', 'settings'];

var done = _.after(saves.length, function() {
  console.log('done saving!');
});

_.forEach(saves, function(type) {
  asyncSave({ 'type': type, 'complete': done });
});
// => logs 'done saving!' after the two async saves have completed

ary source npm

_.ary(func, [n=func.length])

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Arguments

  1. func (Function)

    The function to cap arguments for.

  2. [n=func.length] (number)

    The arity cap.

Returns (Function)

Returns the new function.

Example

_.map(['6', '8', '10'], _.ary(parseInt, 1));
// => [6, 8, 10]

before source npm

_.before(n, func)

Creates a function that invokes func, with the this binding and arguments of the created function, while it's called less than n times. Subsequent calls to the created function return the result of the last func invocation.

Arguments

  1. n (number)

    The number of calls at which func is no longer invoked.

  2. func (Function)

    The function to restrict.

Returns (Function)

Returns the new restricted function.

Example

jQuery('#add').on('click', _.before(5, addContactToList));
// => allows adding up to 4 contacts to the list

bind source npm

_.bind(func, thisArg, [partials])

Creates a function that invokes func with the this binding of thisArg and prepends any additional _.bind arguments to those provided to the bound function.

The _.bind.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Note: Unlike native Function#bind this method doesn't set the "length" property of bound functions.

Arguments

  1. func (Function)

    The function to bind.

  2. thisArg (*)

    The this binding of func.

  3. [partials] (...*)

    The arguments to be partially applied.

Returns (Function)

Returns the new bound function.

Example

var greet = function(greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
};

var object = { 'user': 'fred' };

var bound = _.bind(greet, object, 'hi');
bound('!');
// => 'hi fred!'

// using placeholders
var bound = _.bind(greet, object, _, '!');
bound('hi');
// => 'hi fred!'

bindAll source npm

_.bindAll(object, methodNames)

Binds methods of an object to the object itself, overwriting the existing method.

Note: This method doesn't set the "length" property of bound functions.

Arguments

  1. object (Object)

    The object to bind and assign the bound methods to.

  2. methodNames (...(string|string[])

    The object method names to bind, specified individually or in arrays.

Returns (Object)

Returns object.

Example

var view = {
  'label': 'docs',
  'onClick': function() {
    console.log('clicked ' + this.label);
  }
};

_.bindAll(view, 'onClick');
jQuery('#docs').on('click', view.onClick);
// => logs 'clicked docs' when the element is clicked

bindKey source npm

_.bindKey(object, key, [partials])

Creates a function that invokes the method at object[key] and prepends any additional _.bindKey arguments to those provided to the bound function.

This method differs from _.bind by allowing bound functions to reference methods that may be redefined or don't yet exist. See Peter Michaux's article for more details.

The _.bindKey.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Arguments

  1. object (Object)

    The object the method belongs to.

  2. key (string)

    The key of the method.

  3. [partials] (...*)

    The arguments to be partially applied.

Returns (Function)

Returns the new bound function.

Example

var object = {
  'user': 'fred',
  'greet': function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};

var bound = _.bindKey(object, 'greet', 'hi');
bound('!');
// => 'hi fred!'

object.greet = function(greeting, punctuation) {
  return greeting + 'ya ' + this.user + punctuation;
};

bound('!');
// => 'hiya fred!'

// using placeholders
var bound = _.bindKey(object, 'greet', _, '!');
bound('hi');
// => 'hiya fred!'

curry source npm

_.curry(func, [arity=func.length])

Creates a function that accepts one or more arguments of func that when called either invokes func returning its result, if all func arguments have been provided, or returns a function that accepts one or more of the remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient.

The _.curry.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for provided arguments.

Note: This method doesn't set the "length" property of curried functions.

Arguments

  1. func (Function)

    The function to curry.

  2. [arity=func.length] (number)

    The arity of func.

Returns (Function)

Returns the new curried function.

Example

var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = _.curry(abc);

curried(1)(2)(3);
// => [1, 2, 3]

curried(1, 2)(3);
// => [1, 2, 3]

curried(1, 2, 3);
// => [1, 2, 3]

// using placeholders
curried(1)(_, 3)(2);
// => [1, 2, 3]

curryRight source npm

_.curryRight(func, [arity=func.length])

This method is like _.curry except that arguments are applied to func in the manner of _.partialRight instead of _.partial.

The _.curryRight.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for provided arguments.

Note: This method doesn't set the "length" property of curried functions.

Arguments

  1. func (Function)

    The function to curry.

  2. [arity=func.length] (number)

    The arity of func.

Returns (Function)

Returns the new curried function.

Example

var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = _.curryRight(abc);

curried(3)(2)(1);
// => [1, 2, 3]

curried(2, 3)(1);
// => [1, 2, 3]

curried(1, 2, 3);
// => [1, 2, 3]

// using placeholders
curried(3)(1, _)(2);
// => [1, 2, 3]

debounce source npm

_.debounce(func, [wait=0], [options])

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function return the result of the last func invocation.

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the the debounced function is invoked more than once during the wait timeout.

See David Corbacho's article for details over the differences between _.debounce and _.throttle.

Arguments

  1. func (Function)

    The function to debounce.

  2. [wait=0] (number)

    The number of milliseconds to delay.

  3. [options] (Object)

    The options object.

  4. [options.leading=false] (boolean)

    Specify invoking on the leading edge of the timeout.

  5. [options.maxWait] (number)

    The maximum time func is allowed to be delayed before it's invoked.

  6. [options.trailing=true] (boolean)

    Specify invoking on the trailing edge of the timeout.

Returns (Function)

Returns the new debounced function.

Example

// avoid costly calculations while the window size is in flux
jQuery(window).on('resize', _.debounce(calculateLayout, 150));

// invoke `sendMail` when the click event is fired, debouncing subsequent calls
jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));

// ensure `batchLog` is invoked once after 1 second of debounced calls
var source = new EventSource('/stream');
jQuery(source).on('message', _.debounce(batchLog, 250, {
  'maxWait': 1000
}));

// cancel a debounced call
var todoChanges = _.debounce(batchLog, 1000);
Object.observe(models.todo, todoChanges);

Object.observe(models, function(changes) {
  if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
    todoChanges.cancel();
  }
}, ['delete']);

// ...at some point `models.todo` is changed
models.todo.completed = true;

// ...before 1 second has passed `models.todo` is deleted
// which cancels the debounced `todoChanges` call
delete models.todo;

defer source npm

_.defer(func, [args])

Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to func when it's invoked.

Arguments

  1. func (Function)

    The function to defer.

  2. [args] (...*)

    The arguments to invoke the function with.

Returns (number)

Returns the timer id.

Example

_.defer(function(text) {
  console.log(text);
}, 'deferred');
// logs 'deferred' after one or more milliseconds

delay source npm

_.delay(func, wait, [args])

Invokes func after wait milliseconds. Any additional arguments are provided to func when it's invoked.

Arguments

  1. func (Function)

    The function to delay.

  2. wait (number)

    The number of milliseconds to delay invocation.

  3. [args] (...*)

    The arguments to invoke the function with.

Returns (number)

Returns the timer id.

Example

_.delay(function(text) {
  console.log(text);
}, 1000, 'later');
// => logs 'later' after one second

flip source npm

_.flip(func)

Creates a function that invokes func with arguments reversed.

Arguments

  1. func (Function)

    The function to flip arguments for.

Returns (Function)

Returns the new function.

Example

var flipped = _.flip(function() {
  return _.toArray(arguments);
});

flipped('a', 'b', 'c', 'd');
// => ['d', 'c', 'b', 'a']

memoize source npm

_.memoize(func, [resolver])

Creates a function that memoizes the result of func. If resolver is provided it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key. The func is invoked with the this binding of the memoized function.

Note: The cache is exposed as the cache property on the memoized function. Its creation may be customized by replacing the _.memoize.Cache constructor with one whose instances implement the Map method interface of get, has, and set.

Arguments

  1. func (Function)

    The function to have its output memoized.

  2. [resolver] (Function)

    The function to resolve the cache key.

Returns (Function)

Returns the new memoizing function.

Example

var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };

var values = _.memoize(_.values);
values(object);
// => [1, 2]

values(other);
// => [3, 4]

object.a = 2;
values(object);
// => [1, 2]

// modifying the result cache
values.cache.set(object, ['a', 'b']);
values(object);
// => ['a', 'b']

// replacing `_.memoize.Cache`
_.memoize.Cache = WeakMap;

modArgs source npm

_.modArgs(func, [transforms])

Creates a function that invokes func with arguments modified by corresponding transforms.

Arguments

  1. func (Function)

    The function to wrap.

  2. [transforms] (...(Function|Function[])

    The functions to transform arguments, specified individually or in arrays.

Returns (Function)

Returns the new function.

Example

function doubled(n) {
  return n * 2;
}

function square(n) {
  return n * n;
}

var modded = _.modArgs(function(x, y) {
  return [x, y];
}, square, doubled);

modded(9, 3);
// => [81, 6]

modded(10, 5);
// => [100, 10]

modArgsSet source npm

_.modArgsSet(func, [transforms])

This method is like _.modArgs except that each of the transforms is provided the complete set of arguments the created function is invoked with.

Arguments

  1. func (Function)

    The function to wrap.

  2. [transforms] (...(Function|Function[])

    The functions to transform arguments, specified individually or in arrays.

Returns (Function)

Returns the new function.

Example

function divide(x, y) {
  return x / y;
}

function multiply(x, y) {
  return x * y;
}

var modded = _.modArgsSet(function(x, y) {
  return [x, y];
}, multiply, divide);

modded(9, 3);
// => [27, 3]

modded(10, 5);
// => [50, 2]

negate source npm

_.negate(predicate)

Creates a function that negates the result of the predicate func. The func predicate is invoked with the this binding and arguments of the created function.

Arguments

  1. predicate (Function)

    The predicate to negate.

Returns (Function)

Returns the new function.

Example

function isEven(n) {
  return n % 2 == 0;
}

_.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
// => [1, 3, 5]

once source npm

_.once(func)

Creates a function that is restricted to invoking func once. Repeat calls to the function return the value of the first call. The func is invoked with the this binding and arguments of the created function.

Arguments

  1. func (Function)

    The function to restrict.

Returns (Function)

Returns the new restricted function.

Example

var initialize = _.once(createApplication);
initialize();
initialize();
// `initialize` invokes `createApplication` once

partial source npm

_.partial(func, [partials])

Creates a function that invokes func with partial arguments prepended to those provided to the new function. This method is like _.bind except it does not alter the this binding.

The _.partial.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Note: This method doesn't set the "length" property of partially applied functions.

Arguments

  1. func (Function)

    The function to partially apply arguments to.

  2. [partials] (...*)

    The arguments to be partially applied.

Returns (Function)

Returns the new partially applied function.

Example

var greet = function(greeting, name) {
  return greeting + ' ' + name;
};

var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// => 'hello fred'

// using placeholders
var greetFred = _.partial(greet, _, 'fred');
greetFred('hi');
// => 'hi fred'

partialRight source npm

_.partialRight(func, [partials])

This method is like _.partial except that partially applied arguments are appended to those provided to the new function.

The _.partialRight.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Note: This method doesn't set the "length" property of partially applied functions.

Arguments

  1. func (Function)

    The function to partially apply arguments to.

  2. [partials] (...*)

    The arguments to be partially applied.

Returns (Function)

Returns the new partially applied function.

Example

var greet = function(greeting, name) {
  return greeting + ' ' + name;
};

var greetFred = _.partialRight(greet, 'fred');
greetFred('hi');
// => 'hi fred'

// using placeholders
var sayHelloTo = _.partialRight(greet, 'hello', _);
sayHelloTo('fred');
// => 'hello fred'

rearg source npm

_.rearg(func, indexes)

Creates a function that invokes func with arguments arranged according to the specified indexes where the argument value at the first index is provided as the first argument, the argument value at the second index is provided as the second argument, and so on.

Arguments

  1. func (Function)

    The function to rearrange arguments for.

  2. indexes (...(number|number[])

    The arranged argument indexes, specified individually or in arrays.

Returns (Function)

Returns the new function.

Example

var rearged = _.rearg(function(a, b, c) {
  return [a, b, c];
}, 2, 0, 1);

rearged('b', 'c', 'a')
// => ['a', 'b', 'c']

rest source npm

_.rest(func, [start=func.length-1])

Creates a function that invokes func with the this binding of the created function and arguments from start and beyond provided as an array.

Note: This method is based on the rest parameter.

Arguments

  1. func (Function)

    The function to apply a rest parameter to.

  2. [start=func.length-1] (number)

    The start position of the rest parameter.

Returns (Function)

Returns the new function.

Example

var say = _.rest(function(what, names) {
  return what + ' ' + _.initial(names).join(', ') +
    (_.size(names) > 1 ? ', & ' : '') + _.last(names);
});

say('hello', 'fred', 'barney', 'pebbles');
// => 'hello fred, barney, & pebbles'

spread source npm

_.spread(func)

Creates a function that invokes func with the this binding of the created function and an array of arguments much like Function#apply.

Note: This method is based on the spread operator.

Arguments

  1. func (Function)

    The function to spread arguments over.

Returns (Function)

Returns the new function.

Example

var say = _.spread(function(who, what) {
  return who + ' says ' + what;
});

say(['fred', 'hello']);
// => 'fred says hello'

// with a Promise
var numbers = Promise.all([
  Promise.resolve(40),
  Promise.resolve(36)
]);

numbers.then(_.spread(function(x, y) {
  return x + y;
}));
// => a Promise of 76

throttle source npm

_.throttle(func, [wait=0], [options])

Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled function return the result of the last func call.

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the the throttled function is invoked more than once during the wait timeout.

See David Corbacho's article for details over the differences between _.throttle and _.debounce.

Arguments

  1. func (Function)

    The function to throttle.

  2. [wait=0] (number)

    The number of milliseconds to throttle invocations to.

  3. [options] (Object)

    The options object.

  4. [options.leading=true] (boolean)

    Specify invoking on the leading edge of the timeout.

  5. [options.trailing=true] (boolean)

    Specify invoking on the trailing edge of the timeout.

Returns (Function)

Returns the new throttled function.

Example

// avoid excessively updating the position while scrolling
jQuery(window).on('scroll', _.throttle(updatePosition, 100));

// invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
  'trailing': false
}));

// cancel a trailing throttled call
jQuery(window).on('popstate', throttled.cancel);

unary source npm

_.unary(func)

Creates a function that accepts up to one argument, ignoring any additional arguments.

Arguments

  1. func (Function)

    The function to cap arguments for.

Returns (Function)

Returns the new function.

Example

_.map(['6', '8', '10'], _.unary(parseInt));
// => [6, 8, 10]

wrap source npm

_.wrap(value, wrapper)

Creates a function that provides value to the wrapper function as its first argument. Any additional arguments provided to the function are appended to those provided to the wrapper function. The wrapper is invoked with the this binding of the created function.

Arguments

  1. value (*)

    The value to wrap.

  2. wrapper (Function)

    The wrapper function.

Returns (Function)

Returns the new function.

Example

var p = _.wrap(_.escape, function(func, text) {
  return '<p>' + func(text) + '</p>';
});

p('fred, barney, & pebbles');
// => '<p>fred, barney, &amp; pebbles</p>'

clone source npm

_.clone(value)

Creates a shallow clone of value.

Note: This method is loosely based on the structured clone algorithm. The enumerable properties of arguments objects and objects created by constructors other than Object are cloned to plain Object objects. An empty object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps.

Arguments

  1. value (*)

    The value to clone.

Returns (*)

Returns the cloned value.

Example

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

var shallow = _.clone(users);
console.log(shallow[0] === users[0]);
// => true

cloneDeep source npm

_.cloneDeep(value)

This method is like _.clone except that it recursively clones value.

Arguments

  1. value (*)

    The value to recursively clone.

Returns (*)

Returns the deep cloned value.

Example

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

var deep = _.cloneDeep(users);
console.log(deep[0] === users[0]);
// => false

cloneDeepWith source npm

_.cloneDeepWith(value, [customizer])

This method is like _.cloneWith except that it recursively clones value.

Arguments

  1. value (*)

    The value to recursively clone.

  2. [customizer] (Function)

    The function to customize cloning.

Returns (*)

Returns the deep cloned value.

Example

function customizer(value) {
  if (_.isElement(value)) {
    return value.cloneNode(true);
  }
}

var el = _.cloneDeep(document.body, customizer);

console.log(el === document.body);
// => false
console.log(el.nodeName);
// => BODY
console.log(el.childNodes.length);
// => 20

cloneWith source npm

_.cloneWith(value, [customizer])

This method is like _.clone except that it accepts customizer which is invoked to produce the cloned value. If customizer returns undefined cloning is handled by the method instead. The customizer is invoked with up to five arguments; (value [, index|key, object, stack]).

Arguments

  1. value (*)

    The value to clone.

  2. [customizer] (Function)

    The function to customize cloning.

Returns (*)

Returns the cloned value.

Example

function customizer(value) {
  if (_.isElement(value)) {
    return value.cloneNode(false);
  }
}

var el = _.clone(document.body, customizer);

console.log(el === document.body);
// => false
console.log(el.nodeName);
// => BODY
console.log(el.childNodes.length);
// => 0

eq source npm

_.eq(value, other)

Performs a SameValueZero comparison between two values to determine if they are equivalent.

Arguments

  1. value (*)

    The value to compare.

  2. other (*)

    The other value to compare.

Returns (boolean)

Returns true if the values are equivalent, else false.

Example

var object = { 'user': 'fred' };
var other = { 'user': 'fred' };

_.eq(object, object);
// => true

_.eq(object, other);
// => false

_.eq('a', 'a');
// => true

_.eq('a', Object('a'));
// => false

_.eq(NaN, NaN);
// => true

gt source npm

_.gt(value, other)

Checks if value is greater than other.

Arguments

  1. value (*)

    The value to compare.

  2. other (*)

    The other value to compare.

Returns (boolean)

Returns true if value is greater than other, else false.

Example

_.gt(3, 1);
// => true

_.gt(3, 3);
// => false

_.gt(1, 3);
// => false

gte source npm

_.gte(value, other)

Checks if value is greater than or equal to other.

Arguments

  1. value (*)

    The value to compare.

  2. other (*)

    The other value to compare.

Returns (boolean)

Returns true if value is greater than or equal to other, else false.

Example

_.gte(3, 1);
// => true

_.gte(3, 3);
// => true

_.gte(1, 3);
// => false

isArguments source npm

_.isArguments(value)

Checks if value is likely an arguments object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isArguments(function() { return arguments; }());
// => true

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

isArray source npm

_.isArray(value)

Checks if value is classified as an Array object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

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

_.isArray(document.body.children);
// => false

_.isArray('abc');
// => false

_.isArray(_.noop);
// => false

isArrayLike source npm

_.isArrayLike(value)

Checks if value is array-like. A value is considered array-like if it's not a function and has a value.length that's an integer greater than or equal to 0 and less than or equal to Number.MAX_SAFE_INTEGER.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is array-like, else false.

Example

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

_.isArrayLike(document.body.children);
// => true

_.isArrayLike('abc');
// => true

_.isArrayLike(_.noop);
// => false

isArrayLikeObject source npm

_.isArrayLikeObject(value)

This method is like _.isArrayLike except that it also checks if value is an object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is an array-like object, else false.

Example

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

_.isArrayLikeObject(document.body.children);
// => true

_.isArrayLikeObject('abc');
// => false

_.isArrayLikeObject(_.noop);
// => false

isBoolean source npm

_.isBoolean(value)

Checks if value is classified as a boolean primitive or object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isBoolean(false);
// => true

_.isBoolean(null);
// => false

isDate source npm

_.isDate(value)

Checks if value is classified as a Date object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isDate(new Date);
// => true

_.isDate('Mon April 23 2012');
// => false

isElement source npm

_.isElement(value)

Checks if value is likely a DOM element.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is a DOM element, else false.

Example

_.isElement(document.body);
// => true

_.isElement('<body>');
// => false

isEmpty source npm

_.isEmpty(value)

Checks if value is empty. A value is considered empty unless it's an arguments object, array, string, or jQuery-like collection with a length greater than 0 or an object with own enumerable properties.

Arguments

  1. value (Array|Object|string)

    The value to inspect.

Returns (boolean)

Returns true if value is empty, else false.

Example

_.isEmpty(null);
// => true

_.isEmpty(true);
// => true

_.isEmpty(1);
// => true

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

_.isEmpty({ 'a': 1 });
// => false

isEqual source npm

_.isEqual(value, other)

Performs a deep comparison between two values to determine if they are equivalent.

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties. Functions and DOM nodes are not supported.

Arguments

  1. value (*)

    The value to compare.

  2. other (*)

    The other value to compare.

Returns (boolean)

Returns true if the values are equivalent, else false.

Example

var object = { 'user': 'fred' };
var other = { 'user': 'fred' };

_.isEqual(object, other);
// => true

object === other;
// => false

isEqualWith source npm

_.isEqualWith(value, other, [customizer])

This method is like _.isEqual except that it accepts customizer which is invoked to compare values. If customizer returns undefined comparisons are handled by the method instead. The customizer is invoked with up to seven arguments:
(objValue, othValue [, index|key, object, other, stack]).

Arguments

  1. value (*)

    The value to compare.

  2. other (*)

    The other value to compare.

  3. [customizer] (Function)

    The function to customize comparisons.

Returns (boolean)

Returns true if the values are equivalent, else false.

Example

function isGreeting(value) {
  return /^h(?:i|ello)$/.test(value);
}

function customizer(objValue, othValue) {
  if (isGreeting(objValue) && isGreeting(othValue)) {
    return true;
  }
}

var array = ['hello', 'goodbye'];
var other = ['hi', 'goodbye'];

_.isEqualWith(array, other, customizer);
// => true

isError source npm

_.isError(value)

Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is an error object, else false.

Example

_.isError(new Error);
// => true

_.isError(Error);
// => false

isFinite source npm

_.isFinite(value)

Checks if value is a finite primitive number.

Note: This method is based on Number.isFinite.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is a finite number, else false.

Example

_.isFinite(3);
// => true

_.isFinite(Number.MAX_VALUE);
// => true

_.isFinite(3.14);
// => true

_.isFinite(Infinity);
// => false

isFunction source npm

_.isFunction(value)

Checks if value is classified as a Function object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isFunction(_);
// => true

_.isFunction(/abc/);
// => false

isInteger source npm

_.isInteger(value)

Checks if value is an integer.

Note: This method is based on Number.isInteger.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is an integer, else false.

Example

_.isInteger(3);
// => true

_.isInteger(Number.MIN_VALUE);
// => false

_.isInteger(Infinity);
// => false

_.isInteger('3');
// => false

isLength source npm

_.isLength(value)

Checks if value is a valid array-like length.

Note: This function is loosely based on ToLength.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is a valid length, else false.

Example

_.isLength(3);
// => true

_.isLength(Number.MIN_VALUE);
// => false

_.isLength(Infinity);
// => false

_.isLength('3');
// => false

isMatch source npm

_.isMatch(object, source)

Performs a deep comparison between object and source to determine if object contains equivalent property values.

Note: This method supports comparing properties of arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Functions and DOM nodes are not supported. Provide a customizer function to extend support for comparing other values.

Arguments

  1. object (Object)

    The object to inspect.

  2. source (Object)

    The object of property values to match.

Returns (boolean)

Returns true if object is a match, else false.

Example

var object = { 'user': 'fred', 'age': 40 };

_.isMatch(object, { 'age': 40 });
// => true

_.isMatch(object, { 'age': 36 });
// => false

isMatchWith source npm

_.isMatchWith(object, source, [customizer])

This method is like _.isMatch except that it accepts customizer which is invoked to compare values. If customizer returns undefined comparisons are handled by the method instead. The customizer is invoked with three arguments: (objValue, srcValue, index|key, object, source).

Arguments

  1. object (Object)

    The object to inspect.

  2. source (Object)

    The object of property values to match.

  3. [customizer] (Function)

    The function to customize comparisons.

Returns (boolean)

Returns true if object is a match, else false.

Example

function isGreeting(value) {
  return /^h(?:i|ello)$/.test(value);
}

function customizer(objValue, srcValue) {
  if (isGreeting(objValue) && isGreeting(srcValue)) {
    return true;
  }
}

var object = { 'greeting': 'hello' };
var source = { 'greeting': 'hi' };

_.isMatchWith(object, source, customizer);
// => true

isNaN source npm

_.isNaN(value)

Checks if value is NaN.

Note: This method is not the same as isNaN which returns true for undefined and other non-numeric values.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is NaN, else false.

Example

_.isNaN(NaN);
// => true

_.isNaN(new Number(NaN));
// => true

isNaN(undefined);
// => true

_.isNaN(undefined);
// => false

isNative source npm

_.isNative(value)

Checks if value is a native function.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is a native function, else false.

Example

_.isNative(Array.prototype.push);
// => true

_.isNative(_);
// => false

isNil source npm

_.isNil(value)

Checks if value is null or undefined.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is nullish, else false.

Example

_.isNil(null);
// => true

_.isNil(void 0);
// => true

_.isNil(NaN);
// => false

isNull source npm

_.isNull(value)

Checks if value is null.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is null, else false.

Example

_.isNull(null);
// => true

_.isNull(void 0);
// => false

isNumber source npm

_.isNumber(value)

Checks if value is classified as a Number primitive or object.

Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isNumber(3);
// => true

_.isNumber(Number.MIN_VALUE);
// => true

_.isNumber(Infinity);
// => true

_.isNumber('3');
// => false

isObject source npm

_.isObject(value)

Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is an object, else false.

Example

_.isObject({});
// => true

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

_.isObject(_.noop);
// => true

_.isObject(null);
// => false

isObjectLike source npm

_.isObjectLike(value)

Checks if value is object-like. A value is object-like if it's not null and has a typeof result of "object".

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is object-like, else false.

Example

_.isObjectLike({});
// => true

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

_.isObjectLike(_.noop);
// => false

_.isObjectLike(null);
// => false

isPlainObject source npm

_.isPlainObject(value)

Checks if value is a plain object, that is, an object created by the Object constructor or one with a [[Prototype]] of null.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is a plain object, else false.

Example

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

_.isPlainObject(new Foo);
// => false

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

_.isPlainObject({ 'x': 0, 'y': 0 });
// => true

_.isPlainObject(Object.create(null));
// => true

isRegExp source npm

_.isRegExp(value)

Checks if value is classified as a RegExp object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isRegExp(/abc/);
// => true

_.isRegExp('/abc/');
// => false

isSafeInteger source npm

_.isSafeInteger(value)

Checks if value is a safe integer. An integer is safe if it's an IEEE-754 double precision number which isn't the result of a rounded unsafe integer.

Note: This method is based on Number.isSafeInteger.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is a safe integer, else false.

Example

_.isSafeInteger(3);
// => true

_.isSafeInteger(Number.MIN_VALUE);
// => false

_.isSafeInteger(Infinity);
// => false

_.isSafeInteger('3');
// => false

isString source npm

_.isString(value)

Checks if value is classified as a String primitive or object.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isString('abc');
// => true

_.isString(1);
// => false

isTypedArray source npm

_.isTypedArray(value)

Checks if value is classified as a typed array.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is correctly classified, else false.

Example

_.isTypedArray(new Uint8Array);
// => true

_.isTypedArray([]);
// => false

isUndefined source npm

_.isUndefined(value)

Checks if value is undefined.

Arguments

  1. value (*)

    The value to check.

Returns (boolean)

Returns true if value is undefined, else false.

Example

_.isUndefined(void 0);
// => true

_.isUndefined(null);
// => false

lt source npm

_.lt(value, other)

Checks if value is less than other.

Arguments

  1. value (*)

    The value to compare.

  2. other (*)

    The other value to compare.

Returns (boolean)

Returns true if value is less than other, else false.

Example

_.lt(1, 3);
// => true

_.lt(3, 3);
// => false

_.lt(3, 1);
// => false

lte source npm

_.lte(value, other)

Checks if value is less than or equal to other.

Arguments

  1. value (*)

    The value to compare.

  2. other (*)

    The other value to compare.

Returns (boolean)

Returns true if value is less than or equal to other, else false.

Example

_.lte(1, 3);
// => true

_.lte(3, 3);
// => true

_.lte(3, 1);
// => false

toArray source npm

_.toArray(value)

Converts value to an array.

Arguments

  1. value (*)

    The value to convert.

Returns (Array)

Returns the converted array.

Example

(function() {
  return _.toArray(arguments).slice(1);
}(1, 2, 3));
// => [2, 3]

toInteger source npm

_.toInteger(value)

Converts value to an integer.

Note: This function is loosely based on ToInteger.

Arguments

  1. value (*)

    The value to convert.

Returns (number)

Returns the converted integer.

Example

_.toInteger(3);
// => 3

_.toInteger(Number.MIN_VALUE);
// => 0

_.toInteger(Infinity);
// => 1.7976931348623157e+308

_.toInteger('3');
// => 3

toLength source npm

_.toLength(value)

Converts value to an integer suitable for use as the length of an array-like object.

Note: This method is based on ToLength.

Arguments

  1. value (*)

    The value to convert.

Example

_.toLength(3);
// => 3

_.toLength(Number.MIN_VALUE);
// => 0

_.toLength(Infinity);
// => 4294967295

_.toLength('3');
// => 3

toNumber source npm

_.toNumber(value)

Converts value to a number.

Arguments

  1. value (*)

    The value to process.

Returns (number)

Returns the number.

Example

_.toNumber(3);
// => 3

_.toNumber(Number.MIN_VALUE);
// => 5e-324

_.toNumber(Infinity);
// => Infinity

_.toNumber('3');
// => 3

toPlainObject source npm

_.toPlainObject(value)

Converts value to a plain object flattening inherited enumerable properties of value to own properties of the plain object.

Arguments

  1. value (*)

    The value to convert.

Returns (Object)

Returns the converted plain object.

Example

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

Foo.prototype.c = 3;

_.assign({ 'a': 1 }, new Foo);
// => { 'a': 1, 'b': 2 }

_.assign({ 'a': 1 }, _.toPlainObject(new Foo));
// => { 'a': 1, 'b': 2, 'c': 3 }

toSafeInteger source npm

_.toSafeInteger(value)

Converts value to a safe integer. A safe integer can be compared and represented correctly.

Arguments

  1. value (*)

    The value to convert.

Returns (number)

Returns the converted integer.

Example

_.toSafeInteger(3);
// => 3

_.toSafeInteger(Number.MIN_VALUE);
// => 0

_.toSafeInteger(Infinity);
// => 9007199254740991

_.toSafeInteger('3');
// => 3

toString source npm

_.toString(value)

Converts value to a string if it's not one. An empty string is returned for null and undefined values. The sign of -0 is preserved.

Arguments

  1. value (*)

    The value to process.

Returns (string)

Returns the string.

Example

_.toString(null);
// => ''

_.toString(-0);
// => '-0'

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

add source npm

_.add(augend, addend)

Adds two numbers.

Arguments

  1. augend (number)

    The first number in an addition.

  2. addend (number)

    The second number in an addition.

Returns (number)

Returns the total.

Example

_.add(6, 4);
// => 10

ceil source npm

_.ceil(number, [precision=0])

Calculates number rounded up to precision.

Arguments

  1. number (number)

    The number to round up.

  2. [precision=0] (number)

    The precision to round up to.

Returns (number)

Returns the rounded up number.

Example

_.ceil(4.006);
// => 5

_.ceil(6.004, 2);
// => 6.01

_.ceil(6040, -2);
// => 6100

floor source npm

_.floor(number, [precision=0])

Calculates number rounded down to precision.

Arguments

  1. number (number)

    The number to round down.

  2. [precision=0] (number)

    The precision to round down to.

Returns (number)

Returns the rounded down number.

Example

_.floor(4.006);
// => 4

_.floor(0.046, 2);
// => 0.04

_.floor(4060, -2);
// => 4000

max source npm

_.max(array)

Gets the maximum value of array. If array is empty or falsey undefined is returned.

Arguments

  1. array (Array)

    The array to iterate over.

Returns (*)

Returns the maximum value.

Example

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

_.max([]);
// => undefined

maxBy source npm

_.maxBy(array, [iteratee=_.identity])

This method is like _.max except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked. The iteratee is invoked with one argument: (value).

Arguments

  1. array (Array)

    The array to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (*)

Returns the maximum value.

Example

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

_.maxBy(users, function(o) { return o.age; });
// => { 'user': 'fred', 'age': 40 }

// using the `_.property` callback shorthand
_.maxBy(users, 'age');
// => { 'user': 'fred', 'age': 40 }

min source npm

_.min(array)

Gets the minimum value of array. If array is empty or falsey undefined is returned.

Arguments

  1. array (Array)

    The array to iterate over.

Returns (*)

Returns the minimum value.

Example

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

_.min([]);
// => undefined

minBy source npm

_.minBy(array, [iteratee=_.identity])

This method is like _.min except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked. The iteratee is invoked with one argument: (value).

Arguments

  1. array (Array)

    The array to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (*)

Returns the minimum value.

Example

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

_.minBy(users, function(o) { return o.age; });
// => { 'user': 'barney', 'age': 36 }

// using the `_.property` callback shorthand
_.minBy(users, 'age');
// => { 'user': 'barney', 'age': 36 }

round source npm

_.round(number, [precision=0])

Calculates number rounded to precision.

Arguments

  1. number (number)

    The number to round.

  2. [precision=0] (number)

    The precision to round to.

Returns (number)

Returns the rounded number.

Example

_.round(4.006);
// => 4

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

_.round(4060, -2);
// => 4100

subtract source npm

_.subtract(minuend, subtrahend)

Subtract two numbers.

Arguments

  1. minuend (number)

    The first number in a subtraction.

  2. subtrahend (number)

    The second number in a subtraction.

Returns (number)

Returns the difference.

Example

_.subtract(6, 4);
// => 2

sum source npm

_.sum(array)

Gets the sum of the values in array.

Arguments

  1. array (Array)

    The array to iterate over.

Returns (number)

Returns the sum.

Example

_.sum([4, 6]);
// => 10

sumBy source npm

_.sumBy(array, [iteratee=_.identity])

This method is like _.sum except that it accepts iteratee which is invoked for each element in array to generate the value to be summed. The iteratee is invoked with one argument: (value).

Arguments

  1. array (Array)

    The array to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per element.

Returns (number)

Returns the sum.

Example

var objects = [
  { 'n': 4 },
  { 'n': 6 }
];

_.sumBy(objects, function(o) { return o.n; });
// => 10

// using the `_.property` callback shorthand
_.sumBy(objects, 'n');
// => 10

stringSize source

stringSize(string)

Gets the number of symbols in string.

Arguments

  1. string (string)

    The string to inspect.

Returns (number)

Returns the string size.

templateSettings.imports._ source

_.templateSettings.imports._

A reference to the lodash function.

clamp source npm

_.clamp(number, [min], max)

Returns a number whose value is limited to the given range specified by min and max.

Arguments

  1. number (number)

    The number whose value is to be limited.

  2. [min] (number)

    The minimum possible value.

  3. max (number)

    The maximum possible value.

Returns (number)

A number in the range [min, max].

Example

_.clamp(-10, -5, 5);
// => -5

_.clamp(10, -5, 5);
// => 5

inRange source npm

_.inRange(number, [start=0], end)

Checks if n is between start and up to but not including, end. If end is not specified it's set to start with start then set to 0. If start is greater than end the params are swapped to support negative ranges.

Arguments

  1. number (number)

    The number to check.

  2. [start=0] (number)

    The start of the range.

  3. end (number)

    The end of the range.

Returns (boolean)

Returns true if number is in the range, else false.

Example

_.inRange(3, 2, 4);
// => true

_.inRange(4, 8);
// => true

_.inRange(4, 2);
// => false

_.inRange(2, 2);
// => false

_.inRange(1.2, 2);
// => true

_.inRange(5.2, 4);
// => false

_.inRange(-3, -2, -6);
// => true

random source npm

_.random([min=0], [max=1], [floating])

Produces a random number between min and max (inclusive). If only one argument is provided a number between 0 and the given number is returned. If floating is true, or either min or max are floats, a floating-point number is returned instead of an integer.

Note: JavaScript follows the IEEE-754 standard for resolving floating-point values which can produce unexpected results.

Arguments

  1. [min=0] (number)

    The minimum possible value.

  2. [max=1] (number)

    The maximum possible value.

  3. [floating] (boolean)

    Specify returning a floating-point number.

Returns (number)

Returns the random number.

Example

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

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

_.random(5, true);
// => a floating-point number between 0 and 5

_.random(1.2, 5.2);
// => a floating-point number between 1.2 and 5.2

assign source npm

_.assign(object, [sources])

Assigns own enumerable properties of source objects to the destination object. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

Note: This method mutates object and is loosely based on Object.assign.

Arguments

  1. object (Object)

    The destination object.

  2. [sources] (...Object)

    The source objects.

Returns (Object)

Returns object.

Example

function Foo() {
  this.c = 3;
}

function Bar() {
  this.e = 5;
}

Foo.prototype.d = 4;
Bar.prototype.f = 6;

_.assign({ 'a': 1 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3, 'e': 5 }

assignIn extend source npm

_.assignIn(object, [sources])

This method is like _.assign except that it iterates over own and inherited source properties.

Note: This method mutates object.

Arguments

  1. object (Object)

    The destination object.

  2. [sources] (...Object)

    The source objects.

Returns (Object)

Returns object.

Example

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

function Bar() {
  this.d = 4;
}

Foo.prototype.c = 3;
Bar.prototype.e = 5;

_.assignIn({ 'a': 1 }, new Foo, new Bar);
// => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }

assignInWith extendWith source npm

_.assignInWith(object, sources, [customizer])

This method is like _.assignIn except that it accepts customizer which is invoked to produce the assigned values. If customizer returns undefined assignment is handled by the method instead. The customizer is invoked with five arguments: (objValue, srcValue, key, object, source).

Note: This method mutates object.

Arguments

  1. object (Object)

    The destination object.

  2. sources (...Object)

    The source objects.

  3. [customizer] (Function)

    The function to customize assigned values.

Returns (Object)

Returns object.

Example

function customizer(objValue, srcValue) {
  return _.isUndefined(objValue) ? srcValue : objValue;
}

var defaults = _.partialRight(_.assignInWith, customizer);

defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
// => { 'a': 1, 'b': 2 }

assignWith source npm

_.assignWith(object, sources, [customizer])

This method is like _.assign except that it accepts customizer which is invoked to produce the assigned values. If customizer returns undefined assignment is handled by the method instead. The customizer is invoked with five arguments: (objValue, srcValue, key, object, source).

Note: This method mutates object.

Arguments

  1. object (Object)

    The destination object.

  2. sources (...Object)

    The source objects.

  3. [customizer] (Function)

    The function to customize assigned values.

Returns (Object)

Returns object.

Example

function customizer(objValue, srcValue) {
  return _.isUndefined(objValue) ? srcValue : objValue;
}

var defaults = _.partialRight(_.assignWith, customizer);

defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
// => { 'a': 1, 'b': 2 }

at source npm

_.at(object, [paths])

Creates an array of values corresponding to paths of object.

Arguments

  1. object (Object)

    The object to iterate over.

  2. [paths] (...(string|string[])

    The property paths of elements to pick, specified individually or in arrays.

Returns (Array)

Returns the new array of picked elements.

Example

var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };

_.at(object, ['a[0].b.c', 'a[1]']);
// => [3, 4]

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

create source npm

_.create(prototype, [properties])

Creates an object that inherits from the given prototype object. If a properties object is provided its own enumerable properties are assigned to the created object.

Arguments

  1. prototype (Object)

    The object to inherit from.

  2. [properties] (Object)

    The properties to assign to the object.

Returns (Object)

Returns the new object.

Example

function Shape() {
  this.x = 0;
  this.y = 0;
}

function Circle() {
  Shape.call(this);
}

Circle.prototype = _.create(Shape.prototype, {
  'constructor': Circle
});

var circle = new Circle;
circle instanceof Circle;
// => true

circle instanceof Shape;
// => true

defaults source npm

_.defaults(object, [sources])

Assigns own and inherited enumerable properties of source objects to the destination object for all destination properties that resolve to undefined. Source objects are applied from left to right. Once a property is set, additional values of the same property are ignored.

Note: This method mutates object.

Arguments

  1. object (Object)

    The destination object.

  2. [sources] (...Object)

    The source objects.

Returns (Object)

Returns object.

Example

_.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
// => { 'user': 'barney', 'age': 36 }

defaultsDeep source npm

_.defaultsDeep(object, [sources])

This method is like _.defaults except that it recursively assigns default properties.

Note: This method mutates object.

Arguments

  1. object (Object)

    The destination object.

  2. [sources] (...Object)

    The source objects.

Returns (Object)

Returns object.

Example

_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
// => { 'user': { 'name': 'barney', 'age': 36 } }

findKey source npm

_.findKey(object, [predicate=_.identity])

This method is like _.find except that it returns the key of the first element predicate returns truthy for instead of the element itself.

Arguments

  1. object (Object)

    The object to search.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (string|undefined)

Returns the key of the matched element, else undefined.

Example

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

_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)

// using the `_.matches` callback shorthand
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'

// using the `_.matchesProperty` callback shorthand
_.findKey(users, ['active', false]);
// => 'fred'

// using the `_.property` callback shorthand
_.findKey(users, 'active');
// => 'barney'

findLastKey source npm

_.findLastKey(object, [predicate=_.identity])

This method is like _.findKey except that it iterates over elements of a collection in the opposite order.

Arguments

  1. object (Object)

    The object to search.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (string|undefined)

Returns the key of the matched element, else undefined.

Example

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

_.findLastKey(users, function(o) { return o.age < 40; });
// => returns 'pebbles' assuming `_.findKey` returns 'barney'

// using the `_.matches` callback shorthand
_.findLastKey(users, { 'age': 36, 'active': true });
// => 'barney'

// using the `_.matchesProperty` callback shorthand
_.findLastKey(users, ['active', false]);
// => 'fred'

// using the `_.property` callback shorthand
_.findLastKey(users, 'active');
// => 'pebbles'

forIn source npm

_.forIn(object, [iteratee=_.identity])

Iterates over own and inherited enumerable properties of an object invoking iteratee for each property. The iteratee is invoked with three arguments:
(value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

Arguments

  1. object (Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

Returns (Object)

Returns object.

Example

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

Foo.prototype.c = 3;

_.forIn(new Foo, function(value, key) {
  console.log(key);
});
// => logs 'a', 'b', then 'c' (iteration order is not guaranteed)

forInRight source npm

_.forInRight(object, [iteratee=_.identity])

This method is like _.forIn except that it iterates over properties of object in the opposite order.

Arguments

  1. object (Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

Returns (Object)

Returns object.

Example

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

Foo.prototype.c = 3;

_.forInRight(new Foo, function(value, key) {
  console.log(key);
});
// => logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'

forOwn source npm

_.forOwn(object, [iteratee=_.identity])

Iterates over own enumerable properties of an object invoking iteratee for each property. The iteratee is invoked with three arguments:
(value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

Arguments

  1. object (Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

Returns (Object)

Returns object.

Example

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

Foo.prototype.c = 3;

_.forOwn(new Foo, function(value, key) {
  console.log(key);
});
// => logs 'a' then 'b' (iteration order is not guaranteed)

forOwnRight source npm

_.forOwnRight(object, [iteratee=_.identity])

This method is like _.forOwn except that it iterates over properties of object in the opposite order.

Arguments

  1. object (Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

Returns (Object)

Returns object.

Example

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

Foo.prototype.c = 3;

_.forOwnRight(new Foo, function(value, key) {
  console.log(key);
});
// => logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'

functions source npm

_.functions(object)

Creates an array of function property names from own enumerable properties of object.

Arguments

  1. object (Object)

    The object to inspect.

Returns (Array)

Returns the new array of property names.

Example

function Foo() {
  this.a = _.constant('a');
  this.b = _.constant('b');
}

Foo.prototype.c = _.constant('c');

_.functions(new Foo);
// => ['a', 'b']

functionsIn source npm

_.functionsIn(object)

Creates an array of function property names from own and inherited enumerable properties of object.

Arguments

  1. object (Object)

    The object to inspect.

Returns (Array)

Returns the new array of property names.

Example

function Foo() {
  this.a = _.constant('a');
  this.b = _.constant('b');
}

Foo.prototype.c = _.constant('c');

_.functionsIn(new Foo);
// => ['a', 'b', 'c']

get source npm

_.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined the defaultValue is used in its place.

Arguments

  1. object (Object)

    The object to query.

  2. path (Array|string)

    The path of the property to get.

  3. [defaultValue] (*)

    The value returned if the resolved value is undefined.

Returns (*)

Returns the resolved value.

Example

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

_.get(object, ['a', '0', 'b', 'c']);
// => 3

_.get(object, 'a.b.c', 'default');
// => 'default'

has source npm

_.has(object, path)

Checks if path is a direct property of object.

Arguments

  1. object (Object)

    The object to query.

  2. path (Array|string)

    The path to check.

Returns (boolean)

Returns true if path exists, else false.

Example

var object = { 'a': { 'b': { 'c': 3 } } };
var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });

_.has(object, 'a');
// => true

_.has(object, 'a.b.c');
// => true

_.has(object, ['a', 'b', 'c']);
// => true

_.has(other, 'a');
// => false

hasIn source npm

_.hasIn(object, path)

Checks if path is a direct or inherited property of object.

Arguments

  1. object (Object)

    The object to query.

  2. path (Array|string)

    The path to check.

Returns (boolean)

Returns true if path exists, else false.

Example

var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });

_.hasIn(object, 'a');
// => true

_.hasIn(object, 'a.b.c');
// => true

_.hasIn(object, ['a', 'b', 'c']);
// => true

_.hasIn(object, 'b');
// => false

invert source npm

_.invert(object, [multiVal])

Creates an object composed of the inverted keys and values of object. If object contains duplicate values, subsequent values overwrite property assignments of previous values unless multiVal is true.

Arguments

  1. object (Object)

    The object to invert.

  2. [multiVal] (boolean)

    Allow multiple values per key.

Returns (Object)

Returns the new inverted object.

Example

var object = { 'a': 1, 'b': 2, 'c': 1 };

_.invert(object);
// => { '1': 'c', '2': 'b' }

// with `multiVal`
_.invert(object, true);
// => { '1': ['a', 'c'], '2': ['b'] }

keys source npm

_.keys(object)

Creates an array of the own enumerable property names of object.

Note: Non-object values are coerced to objects. See the ES spec for more details.

Arguments

  1. object (Object)

    The object to query.

Returns (Array)

Returns the array of property names.

Example

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

Foo.prototype.c = 3;

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

_.keys('hi');
// => ['0', '1']

keysIn source npm

_.keysIn(object)

Creates an array of the own and inherited enumerable property names of object.

Note: Non-object values are coerced to objects.

Arguments

  1. object (Object)

    The object to query.

Returns (Array)

Returns the array of property names.

Example

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

Foo.prototype.c = 3;

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

mapKeys source npm

_.mapKeys(object, [iteratee=_.identity])

The opposite of _.mapValues; this method creates an object with the same values as object and keys generated by running each own enumerable property of object through iteratee.

Arguments

  1. object (Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Object)

Returns the new mapped object.

Example

_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
  return key + value;
});
// => { 'a1': 1, 'b2': 2 }

mapValues source npm

_.mapValues(object, [iteratee=_.identity])

Creates an object with the same keys as object and values generated by running each own enumerable property of object through iteratee. The iteratee function is invoked with three arguments: (value, key, object).

Arguments

  1. object (Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function|Object|string)

    The function invoked per iteration.

Returns (Object)

Returns the new mapped object.

Example

var users = {
  'fred':    { 'user': 'fred',    'age': 40 },
  'pebbles': { 'user': 'pebbles', 'age': 1 }
};

_.mapValues(users, function(o) { return o.age; });
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)

// using the `_.property` callback shorthand
_.mapValues(users, 'age');
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)

merge source npm

_.merge(object, [sources])

Recursively merges own and inherited enumerable properties of source objects into the destination object, skipping source properties that resolve to undefined. Array and plain object properties are merged recursively. Other objects and value types are overriden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

Note: This method mutates object.

Arguments

  1. object (Object)

    The destination object.

  2. [sources] (...Object)

    The source objects.

Returns (Object)

Returns object.

Example

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

var ages = {
  'data': [{ 'age': 36 }, { 'age': 40 }]
};

_.merge(users, ages);
// => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }

mergeWith source npm

_.mergeWith(object, sources, customizer)

This method is like _.merge except that it accepts customizer which is invoked to produce the merged values of the destination and source properties. If customizer returns undefined merging is handled by the method instead. The customizer is invoked with seven arguments:
(objValue, srcValue, key, object, source, stack).

Arguments

  1. object (Object)

    The destination object.

  2. sources (...Object)

    The source objects.

  3. customizer (Function)

    The function to customize assigned values.

Returns (Object)

Returns object.

Example

function customizer(objValue, srcValue) {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
}

var object = {
  'fruits': ['apple'],
  'vegetables': ['beet']
};

var other = {
  'fruits': ['banana'],
  'vegetables': ['carrot']
};

_.mergeWith(object, other, customizer);
// => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }

omit source npm

_.omit(object, [props])

The opposite of _.pick; this method creates an object composed of the own and inherited enumerable properties of object that are not omitted.

Arguments

  1. object (Object)

    The source object.

  2. [props] (...(string|string[])

    The property names to omit, specified individually or in arrays..

Returns (Object)

Returns the new object.

Example

var object = { 'user': 'fred', 'age': 40 };

_.omit(object, 'user');
// => { 'age': 40 }

omitBy source npm

_.omitBy(object, [predicate=_.identity])

The opposite of _.pickBy; this method creates an object composed of the own and inherited enumerable properties of object that predicate doesn't return truthy for.

Arguments

  1. object (Object)

    The source object.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per property.

Returns (Object)

Returns the new object.

Example

var object = { 'user': 'fred', 'age': 40 };

_.omitBy(object, _.isNumber);
// => { 'user': 'fred' }

pairs source npm

_.pairs(object)

Creates an array of own enumerable key-value pairs for object.

Arguments

  1. object (Object)

    The object to query.

Returns (Array)

Returns the new array of key-value pairs.

Example

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

Foo.prototype.c = 3;

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

pairsIn source npm

_.pairsIn(object)

Creates an array of own and inherited enumerable key-value pairs for object.

Arguments

  1. object (Object)

    The object to query.

Returns (Array)

Returns the new array of key-value pairs.

Example

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

Foo.prototype.c = 3;

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

pick source npm

_.pick(object, [props])

Creates an object composed of the picked object properties.

Arguments

  1. object (Object)

    The source object.

  2. [props] (...(string|string[])

    The property names to pick, specified individually or in arrays.

Returns (Object)

Returns the new object.

Example

var object = { 'user': 'fred', 'age': 40 };

_.pick(object, 'user');
// => { 'user': 'fred' }

pickBy source npm

_.pickBy(object, [predicate=_.identity])

Creates an object composed of the object properties predicate returns truthy for. The predicate is invoked with one argument: (value).

Arguments

  1. object (Object)

    The source object.

  2. [predicate=_.identity] (Function|Object|string)

    The function invoked per property.

Returns (Object)

Returns the new object.

Example

var object = { 'user': 'fred', 'age': 40 };

_.pickBy(object, _.isNumber);
// => { 'age': 40 }

result source npm

_.result(object, path, [defaultValue])

This method is like _.get except that if the resolved value is a function it's invoked with the this binding of its parent object and its result is returned.

Arguments

  1. object (Object)

    The object to query.

  2. path (Array|string)

    The path of the property to resolve.

  3. [defaultValue] (*)

    The value returned if the resolved value is undefined.

Returns (*)

Returns the resolved value.

Example

var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };

_.result(object, 'a[0].b.c1');
// => 3

_.result(object, 'a[0].b.c2');
// => 4

_.result(object, 'a.b.c', 'default');
// => 'default'

_.result(object, 'a.b.c', _.constant('default'));
// => 'default'

set source npm

_.set(object, path, value)

Sets the value at path of object. If a portion of path doesn't exist it's created.

Arguments

  1. object (Object)

    The object to modify.

  2. path (Array|string)

    The path of the property to set.

  3. value (*)

    The value to set.

Returns (Object)

Returns object.

Example

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4

_.set(object, 'x[0].y.z', 5);
console.log(object.x[0].y.z);
// => 5

setWith source npm

_.setWith(object, path, value, [customizer])

This method is like _.set except that it accepts customizer which is invoked to produce the objects of path. If customizer returns undefined path creation is handled by the method instead. The customizer is invoked with three arguments: (nsValue, key, nsObject).

Arguments

  1. object (Object)

    The object to modify.

  2. path (Array|string)

    The path of the property to set.

  3. value (*)

    The value to set.

  4. [customizer] (Function)

    The function to customize assigned values.

Returns (Object)

Returns object.

Example

function customizer(nsValue) {
  if (!_.isObject(nsValue)) {
    return {};
  }
}

_.setWith({ '0': { 'length': 2 } }, '[0][1][2]', 3, customizer);
// => { '0': { '1': { '2': 3 }, 'length': 2 } }

transform source npm

_.transform(object, [iteratee=_.identity], [accumulator])

An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of running each of its own enumerable properties through iteratee, with each invocation potentially mutating the accumulator object. The iteratee is invoked with four arguments:
(accumulator, value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

Arguments

  1. object (Array|Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

  3. [accumulator] (*)

    The custom accumulator value.

Returns (*)

Returns the accumulated value.

Example

_.transform([2, 3, 4], function(result, n) {
  result.push(n *= n);
  return n % 2 == 0;
});
// => [4, 9]

_.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
});
// => { '1': ['a', 'c'], '2': ['b'] }

unset source npm

_.unset(object, path)

Removes the property at path of object.

Arguments

  1. object (Object)

    The object to modify.

  2. path (Array|string)

    The path of the property to unset.

Returns (boolean)

Returns true if the property is deleted, else false.

Example

var object = { 'a': [{ 'b': { 'c': 7 } }] };
_.unset(object, 'a[0].b.c');
// => true

console.log(object);
// => { 'a': [{ 'b': {} }] };

_.unset(object, 'a[0].b.c');
// => true

console.log(object);
// => { 'a': [{ 'b': {} }] };

values source npm

_.values(object)

Creates an array of the own enumerable property values of object.

Note: Non-object values are coerced to objects.

Arguments

  1. object (Object)

    The object to query.

Returns (Array)

Returns the array of property values.

Example

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

Foo.prototype.c = 3;

_.values(new Foo);
// => [1, 2] (iteration order is not guaranteed)

_.values('hi');
// => ['h', 'i']

valuesIn source npm

_.valuesIn(object)

Creates an array of the own and inherited enumerable property values of object.

Note: Non-object values are coerced to objects.

Arguments

  1. object (Object)

    The object to query.

Returns (Array)

Returns the array of property values.

Example

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

Foo.prototype.c = 3;

_.valuesIn(new Foo);
// => [1, 2, 3] (iteration order is not guaranteed)

templateSettings source npm

_.templateSettings

(Object): By default, the template delimiters used by lodash are like those in embedded Ruby (ERB). Change the following template settings to use alternative delimiters.

templateSettings.escape source

_.templateSettings.escape

(RegExp): Used to detect data property values to be HTML-escaped.

templateSettings.evaluate source

_.templateSettings.evaluate

(RegExp): Used to detect code to be evaluated.

templateSettings.imports source

_.templateSettings.imports

(Object): Used to import variables into the compiled template.

templateSettings.interpolate source

_.templateSettings.interpolate

(RegExp): Used to detect data property values to inject.

templateSettings.variable source

_.templateSettings.variable

(string): Used to reference the data object in the template text.

VERSION source

_.VERSION

(string): The semantic version number.

camelCase source npm

_.camelCase([string=''])

Converts string to camel case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the camel cased string.

Example

_.camelCase('Foo Bar');
// => 'fooBar'

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

_.camelCase('__foo_bar__');
// => 'fooBar'

capitalize source npm

_.capitalize([string=''])

Converts the first character of string to upper case and the remaining to lower case.

Arguments

  1. [string=''] (string)

    The string to capitalize.

Returns (string)

Returns the capitalized string.

Example

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

deburr source npm

_.deburr([string=''])

Deburrs string by converting latin-1 supplementary letters#Character_table) to basic latin letters and removing combining diacritical marks.

Arguments

  1. [string=''] (string)

    The string to deburr.

Returns (string)

Returns the deburred string.

Example

_.deburr('déjà vu');
// => 'deja vu'

endsWith source npm

_.endsWith([string=''], [target], [position=string.length])

Checks if string ends with the given target string.

Arguments

  1. [string=''] (string)

    The string to search.

  2. [target] (string)

    The string to search for.

  3. [position=string.length] (number)

    The position to search from.

Returns (boolean)

Returns true if string ends with target, else false.

Example

_.endsWith('abc', 'c');
// => true

_.endsWith('abc', 'b');
// => false

_.endsWith('abc', 'b', 2);
// => true

escape source npm

_.escape([string=''])

Converts the characters "&", "<", ">", '"', "'", and "`" in string to their corresponding HTML entities.

Note: No other characters are escaped. To escape additional characters use a third-party library like he.

Though the ">" character is escaped for symmetry, characters like ">" and "/" don't need escaping in HTML and have no special meaning unless they're part of a tag or unquoted attribute value. See Mathias Bynens's article (under "semi-related fun fact") for more details.

Backticks are escaped because in Internet Explorer < 9, they can break out of attribute values or HTML comments. See #59, #102, #108, and #133 of the HTML5 Security Cheatsheet for more details.

When working with HTML you should always quote attribute values to reduce XSS vectors.

Arguments

  1. [string=''] (string)

    The string to escape.

Returns (string)

Returns the escaped string.

Example

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

escapeRegExp source npm

_.escapeRegExp([string=''])

Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in string.

Arguments

  1. [string=''] (string)

    The string to escape.

Returns (string)

Returns the escaped string.

Example

_.escapeRegExp('[lodash](https://lodash.com/)');
// => '\[lodash\]\(https://lodash\.com/\)'

kebabCase source npm

_.kebabCase([string=''])

Converts string to kebab case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the kebab cased string.

Example

_.kebabCase('Foo Bar');
// => 'foo-bar'

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

_.kebabCase('__foo_bar__');
// => 'foo-bar'

lowerCase source npm

_.lowerCase([string=''])

Converts string, as space separated words, to lower case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the lower cased string.

Example

_.lowerCase('--Foo-Bar');
// => 'foo bar'

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

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

lowerFirst source npm

_.lowerFirst([string=''])

Converts the first character of string to lower case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the converted string.

Example

_.lowerFirst('Fred');
// => 'fred'

_.lowerFirst('FRED');
// => 'fRED'

pad source npm

_.pad([string=''], [length=0], [chars=' '])

Pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length.

Arguments

  1. [string=''] (string)

    The string to pad.

  2. [length=0] (number)

    The padding length.

  3. [chars=' '] (string)

    The string used as padding.

Returns (string)

Returns the padded string.

Example

_.pad('abc', 8);
// => '  abc   '

_.pad('abc', 8, '_-');
// => '_-abc_-_'

_.pad('abc', 3);
// => 'abc'

padLeft source npm

_.padLeft([string=''], [length=0], [chars=' '])

Pads string on the left side if it's shorter than length. Padding characters are truncated if they exceed length.

Arguments

  1. [string=''] (string)

    The string to pad.

  2. [length=0] (number)

    The padding length.

  3. [chars=' '] (string)

    The string used as padding.

Returns (string)

Returns the padded string.

Example

_.padLeft('abc', 6);
// => '   abc'

_.padLeft('abc', 6, '_-');
// => '_-_abc'

_.padLeft('abc', 3);
// => 'abc'

padRight source npm

_.padRight([string=''], [length=0], [chars=' '])

Pads string on the right side if it's shorter than length. Padding characters are truncated if they exceed length.

Arguments

  1. [string=''] (string)

    The string to pad.

  2. [length=0] (number)

    The padding length.

  3. [chars=' '] (string)

    The string used as padding.

Returns (string)

Returns the padded string.

Example

_.padRight('abc', 6);
// => 'abc   '

_.padRight('abc', 6, '_-');
// => 'abc_-_'

_.padRight('abc', 3);
// => 'abc'

parseInt source npm

_.parseInt(string, [radix])

Converts string to an integer of the specified radix. If radix is undefined or 0, a radix of 10 is used unless value is a hexadecimal, in which case a radix of 16 is used.

Note: This method aligns with the ES5 implementation of parseInt.

Arguments

  1. string (string)

    The string to convert.

  2. [radix] (number)

    The radix to interpret value by.

Returns (number)

Returns the converted integer.

Example

_.parseInt('08');
// => 8

_.map(['6', '08', '10'], _.parseInt);
// => [6, 8, 10]

repeat source npm

_.repeat([string=''], [n=0])

Repeats the given string n times.

Arguments

  1. [string=''] (string)

    The string to repeat.

  2. [n=0] (number)

    The number of times to repeat the string.

Returns (string)

Returns the repeated string.

Example

_.repeat('*', 3);
// => '***'

_.repeat('abc', 2);
// => 'abcabc'

_.repeat('abc', 0);
// => ''

snakeCase source npm

_.snakeCase([string=''])

Converts string to snake case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the snake cased string.

Example

_.snakeCase('Foo Bar');
// => 'foo_bar'

_.snakeCase('fooBar');
// => 'foo_bar'

_.snakeCase('--foo-bar');
// => 'foo_bar'

startCase source npm

_.startCase([string=''])

Converts string to start case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the start cased string.

Example

_.startCase('--foo-bar');
// => 'Foo Bar'

_.startCase('fooBar');
// => 'Foo Bar'

_.startCase('__foo_bar__');
// => 'Foo Bar'

startsWith source npm

_.startsWith([string=''], [target], [position=0])

Checks if string starts with the given target string.

Arguments

  1. [string=''] (string)

    The string to search.

  2. [target] (string)

    The string to search for.

  3. [position=0] (number)

    The position to search from.

Returns (boolean)

Returns true if string starts with target, else false.

Example

_.startsWith('abc', 'a');
// => true

_.startsWith('abc', 'b');
// => false

_.startsWith('abc', 'b', 1);
// => true

template source npm

_.template([string=''], [options])

Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data properties may be accessed as free variables in the template. If a setting object is provided it takes precedence over _.templateSettings values.

Note: In the development build _.template utilizes sourceURLs for easier debugging.

For more information on precompiling templates see lodash's custom builds documentation.

For more information on Chrome extension sandboxes see Chrome's extensions documentation.

Arguments

  1. [string=''] (string)

    The template string.

  2. [options] (Object)

    The options object.

  3. [options.escape] (RegExp)

    The HTML "escape" delimiter.

  4. [options.evaluate] (RegExp)

    The "evaluate" delimiter.

  5. [options.imports] (Object)

    An object to import into the template as free variables.

  6. [options.interpolate] (RegExp)

    The "interpolate" delimiter.

  7. [options.sourceURL] (string)

    The sourceURL of the template's compiled source.

  8. [options.variable] (string)

    The data object variable name.

Returns (Function)

Returns the compiled template function.

Example

// using the "interpolate" delimiter to create a compiled template
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'

// using the HTML "escape" delimiter to escape data property values
var compiled = _.template('<b><%- value %></b>');
compiled({ 'value': '<script>' });
// => '<b>&lt;script&gt;</b>'

// using the "evaluate" delimiter to execute JavaScript and generate HTML
var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
compiled({ 'users': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'

// using the internal `print` function in "evaluate" delimiters
var compiled = _.template('<% print("hello " + user); %>!');
compiled({ 'user': 'barney' });
// => 'hello barney!'

// using the ES delimiter as an alternative to the default "interpolate" delimiter
var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles!'

// using custom template delimiters
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'

// using backslashes to treat delimiters as plain text
var compiled = _.template('<%= "\\<%- value %\\>" %>');
compiled({ 'value': 'ignored' });
// => '<%- value %>'

// using the `imports` option to import `jQuery` as `jq`
var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
compiled({ 'users': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'

// using the `sourceURL` option to specify a custom sourceURL for the template
var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
compiled(data);
// => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector

// using the `variable` option to ensure a with-statement isn't used in the compiled template
var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
compiled.source;
// => function(data) {
//   var __t, __p = '';
//   __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
//   return __p;
// }

// using the `source` property to inline compiled templates for meaningful
// line numbers in error messages and a stack trace
fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  var JST = {\
    "main": ' + _.template(mainText).source + '\
  };\
');

toLower source npm

_.toLower([string=''])

Converts string, as a whole, to lower case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the lower cased string.

Example

_.toLower('--Foo-Bar');
// => '--foo-bar'

_.toLower('fooBar');
// => 'foobar'

_.toLower('__FOO_BAR__');
// => '__foo_bar__'

toUpper source npm

_.toUpper([string=''])

Converts string, as a whole, to upper case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the upper cased string.

Example

_.toUpper('--foo-bar');
// => '--FOO-BAR'

_.toUpper('fooBar');
// => 'FOOBAR'

_.toUpper('__foo_bar__');
// => '__FOO_BAR__'

trim source npm

_.trim([string=''], [chars=whitespace])

Removes leading and trailing whitespace or specified characters from string.

Arguments

  1. [string=''] (string)

    The string to trim.

  2. [chars=whitespace] (string)

    The characters to trim.

Returns (string)

Returns the trimmed string.

Example

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

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

_.map(['  foo  ', '  bar  '], _.trim);
// => ['foo', 'bar']

trimLeft source npm

_.trimLeft([string=''], [chars=whitespace])

Removes leading whitespace or specified characters from string.

Arguments

  1. [string=''] (string)

    The string to trim.

  2. [chars=whitespace] (string)

    The characters to trim.

Returns (string)

Returns the trimmed string.

Example

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

_.trimLeft('-_-abc-_-', '_-');
// => 'abc-_-'

trimRight source npm

_.trimRight([string=''], [chars=whitespace])

Removes trailing whitespace or specified characters from string.

Arguments

  1. [string=''] (string)

    The string to trim.

  2. [chars=whitespace] (string)

    The characters to trim.

Returns (string)

Returns the trimmed string.

Example

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

_.trimRight('-_-abc-_-', '_-');
// => '-_-abc'

truncate source npm

_.truncate([string=''], [options])

Truncates string if it's longer than the given maximum string length. The last characters of the truncated string are replaced with the omission string which defaults to "...".

Arguments

  1. [string=''] (string)

    The string to truncate.

  2. [options] (Object)

    The options object.

  3. [options.length=30] (number)

    The maximum string length.

  4. [options.omission='...'] (string)

    The string to indicate text is omitted.

  5. [options.separator] (RegExp|string)

    The separator pattern to truncate to.

Returns (string)

Returns the truncated string.

Example

_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'

_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
});
// => 'hi-diddly-ho there,...'

_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': /,? +/
});
// => 'hi-diddly-ho there...'

_.truncate('hi-diddly-ho there, neighborino', {
  'omission': ' [...]'
});
// => 'hi-diddly-ho there, neig [...]'

unescape source npm

_.unescape([string=''])

The inverse of _.escape; this method converts the HTML entities &amp;, &lt;, &gt;, &quot;, &#39;, and &#96; in string to their corresponding characters.

Note: No other HTML entities are unescaped. To unescape additional HTML entities use a third-party library like he.

Arguments

  1. [string=''] (string)

    The string to unescape.

Returns (string)

Returns the unescaped string.

Example

_.unescape('fred, barney, &amp; pebbles');
// => 'fred, barney, & pebbles'

upperCase source npm

_.upperCase([string=''])

Converts string, as space separated words, to upper case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the upper cased string.

Example

_.upperCase('--foo-bar');
// => 'FOO BAR'

_.upperCase('fooBar');
// => 'FOO BAR'

_.upperCase('__foo_bar__');
// => 'FOO BAR'

upperFirst source npm

_.upperFirst([string=''])

Converts the first character of string to upper case.

Arguments

  1. [string=''] (string)

    The string to convert.

Returns (string)

Returns the converted string.

Example

_.upperFirst('fred');
// => 'Fred'

_.upperFirst('FRED');
// => 'FRED'

words source npm

_.words([string=''], [pattern])

Splits string into an array of its words.

Arguments

  1. [string=''] (string)

    The string to inspect.

  2. [pattern] (RegExp|string)

    The pattern to match words.

Returns (Array)

Returns the words of string.

Example

_.words('fred, barney, & pebbles');
// => ['fred', 'barney', 'pebbles']

_.words('fred, barney, & pebbles', /[^, ]+/g);
// => ['fred', 'barney', '&', 'pebbles']

attempt source npm

_.attempt(func)

Attempts to invoke func, returning either the result or the caught error object. Any additional arguments are provided to func when it's invoked.

Arguments

  1. func (Function)

    The function to attempt.

Returns (*)

Returns the func result or error object.

Example

// avoid throwing errors for invalid selectors
var elements = _.attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');

if (_.isError(elements)) {
  elements = [];
}

conforms source npm

_.conforms(source)

Creates a function that invokes the predicate properties of source with the corresponding property values of a given object, returning true if all predicates return truthy, else false.

Arguments

  1. source (Object)

    The object of property predicates to conform to.

Returns (Function)

Returns the new function.

Example

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

_.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));
// => [{ 'user': 'fred', 'age': 40 }]

conj source npm

_.conj(predicates)

Creates a function that checks if all of the predicates return truthy when invoked with the arguments provided to the created function.

Arguments

  1. predicates (...(Function|Function[])

    The predicates to check.

Returns (Function)

Returns the new function.

Example

var conjed = _.conj(Boolean, isFinite);

conjed('1');
// => true

conjed(null);
// => false

conjed(NaN);
// => false

constant source npm

_.constant(value)

Creates a function that returns value.

Arguments

  1. value (*)

    The value to return from the new function.

Returns (Function)

Returns the new function.

Example

var object = { 'user': 'fred' };
var getter = _.constant(object);

getter() === object;
// => true

disj source npm

_.disj(predicates)

Creates a function that checks if any of the predicates return truthy when invoked with the arguments provided to the created function.

Arguments

  1. predicates (...(Function|Function[])

    The predicates to check.

Returns (Function)

Returns the new function.

Example

var disjed = _.disj(Boolean, isFinite);

disjed('1');
// => true

disjed(null);
// => true

disjed(NaN);
// => false

flow source npm

_.flow([funcs])

Creates a function that returns the result of invoking the provided functions with the this binding of the created function, where each successive invocation is supplied the return value of the previous.

Arguments

  1. [funcs] (...(Function|Function[])

    Functions to invoke.

Returns (Function)

Returns the new function.

Example

function square(n) {
  return n * n;
}

var addSquare = _.flow(_.add, square);
addSquare(1, 2);
// => 9

flowRight source npm

_.flowRight([funcs])

This method is like _.flow except that it creates a function that invokes the provided functions from right to left.

Arguments

  1. [funcs] (...(Function|Function[])

    Functions to invoke.

Returns (Function)

Returns the new function.

Example

function square(n) {
  return n * n;
}

var addSquare = _.flowRight(square, _.add);
addSquare(1, 2);
// => 9

identity source npm

_.identity(value)

This method returns the first argument provided to it.

Arguments

  1. value (*)

    Any value.

Returns (*)

Returns value.

Example

var object = { 'user': 'fred' };

_.identity(object) === object;
// => true

iteratee source npm

_.iteratee([func=_.identity])

Creates a function that invokes func with the arguments of the created function. If func is a property name the created callback returns the property value for a given element. If func is an object the created callback returns true for elements that contain the equivalent object properties, otherwise it returns false.

Arguments

  1. [func=_.identity] (*)

    The value to convert to a callback.

Returns (Function)

Returns the callback.

Example

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

// wrap to create custom callback shorthands
_.iteratee = _.wrap(_.iteratee, function(callback, func, thisArg) {
  var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
  if (!match) {
    return callback(func, thisArg);
  }
  return function(object) {
    return match[2] == 'gt'
      ? object[match[1]] > match[3]
      : object[match[1]] < match[3];
  };
});

_.filter(users, 'age__gt36');
// => [{ 'user': 'fred', 'age': 40 }]

juxt source npm

_.juxt(iteratees)

Creates a function that invokes iteratees with the arguments provided to the created function and returns their results.

Arguments

  1. iteratees (...(Function|Function[])

    The iteratees to invoke.

Returns (Function)

Returns the new function.

Example

var juxted = _.juxt(Math.max, Math.min);

juxted(1, 2, 3, 4);
// => [4, 1]

matches source npm

_.matches(source)

Creates a function that performs a deep partial comparison between a given object and source, returning true if the given object has equivalent property values, else false.

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own and inherited enumerable properties. For comparing a single value see _.matchesProperty.

Arguments

  1. source (Object)

    The object of property values to match.

Returns (Function)

Returns the new function.

Example

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

_.filter(users, _.matches({ 'age': 40, 'active': false }));
// => [{ 'user': 'fred', 'age': 40, 'active': false }]

matchesProperty source npm

_.matchesProperty(path, srcValue)

Creates a function that performs a deep partial comparison between the value at path of a given object to srcValue, returning true if the object value is equivalent, else false.

Note: This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings.

Arguments

  1. path (Array|string)

    The path of the property to get.

  2. srcValue (*)

    The value to match.

Returns (Function)

Returns the new function.

Example

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

_.find(users, _.matchesProperty('user', 'fred'));
// => { 'user': 'fred' }

method source npm

_.method(path, [args])

Creates a function that invokes the method at path of a given object. Any additional arguments are provided to the invoked method.

Arguments

  1. path (Array|string)

    The path of the method to invoke.

  2. [args] (...*)

    The arguments to invoke the method with.

Returns (Function)

Returns the new function.

Example

var objects = [
  { 'a': { 'b': { 'c': _.constant(2) } } },
  { 'a': { 'b': { 'c': _.constant(1) } } }
];

_.map(objects, _.method('a.b.c'));
// => [2, 1]

_.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
// => [1, 2]

methodOf source npm

_.methodOf(object, [args])

The opposite of _.method; this method creates a function that invokes the method at a given path of object. Any additional arguments are provided to the invoked method.

Arguments

  1. object (Object)

    The object to query.

  2. [args] (...*)

    The arguments to invoke the method with.

Returns (Function)

Returns the new function.

Example

var array = _.times(3, _.constant),
    object = { 'a': array, 'b': array, 'c': array };

_.map(['a[2]', 'c[0]'], _.methodOf(object));
// => [2, 0]

_.map([['a', '2'], ['c', '0']], _.methodOf(object));
// => [2, 0]

mixin source npm

_.mixin([object=lodash], source, [options])

Adds all own enumerable function properties of a source object to the destination object. If object is a function then methods are added to its prototype as well.

Note: Use _.runInContext to create a pristine lodash function to avoid conflicts caused by modifying the original.

Arguments

  1. [object=lodash] (Function|Object)

    The destination object.

  2. source (Object)

    The object of functions to add.

  3. [options] (Object)

    The options object.

  4. [options.chain=true] (boolean)

    Specify whether the functions added are chainable.

Returns (Function|Object)

Returns object.

Example

function vowels(string) {
  return _.filter(string, function(v) {
    return /[aeiou]/i.test(v);
  });
}

_.mixin({ 'vowels': vowels });
_.vowels('fred');
// => ['e']

_('fred').vowels().value();
// => ['e']

_.mixin({ 'vowels': vowels }, { 'chain': false });
_('fred').vowels();
// => ['e']

noConflict source npm

_.noConflict()

Reverts the _ variable to its previous value and returns a reference to the lodash function.

Returns (Function)

Returns the lodash function.

Example

var lodash = _.noConflict();

noop source npm

_.noop()

A no-operation function that returns undefined regardless of the arguments it receives.

Example

var object = { 'user': 'fred' };

_.noop(object) === undefined;
// => true

nthArg source npm

_.nthArg([n=0])

Creates a function that returns its nth argument.

Arguments

  1. [n=0] (number)

    The index of the argument to return.

Returns (Function)

Returns the new function.

Example

var func = _.nthArg(1);

func('a', 'b', 'c');
// => 'b'

property source npm

_.property(path)

Creates a function that returns the value at path of a given object.

Arguments

  1. path (Array|string)

    The path of the property to get.

Returns (Function)

Returns the new function.

Example

var objects = [
  { 'a': { 'b': { 'c': 2 } } },
  { 'a': { 'b': { 'c': 1 } } }
];

_.map(objects, _.property('a.b.c'));
// => [2, 1]

_.map(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
// => [1, 2]

propertyOf source npm

_.propertyOf(object)

The opposite of _.property; this method creates a function that returns the value at a given path of object.

Arguments

  1. object (Object)

    The object to query.

Returns (Function)

Returns the new function.

Example

var array = [0, 1, 2],
    object = { 'a': array, 'b': array, 'c': array };

_.map(['a[2]', 'c[0]'], _.propertyOf(object));
// => [2, 0]

_.map([['a', '2'], ['c', '0']], _.propertyOf(object));
// => [2, 0]

range source npm

_.range([start=0], end, [step=1])

Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. If end is not specified it's set to start with start then set to 0. If end is less than start a zero-length range is created unless a negative step is specified.

Note: JavaScript follows the IEEE-754 standard for resolving floating-point values which can produce unexpected results.

Arguments

  1. [start=0] (number)

    The start of the range.

  2. end (number)

    The end of the range.

  3. [step=1] (number)

    The value to increment or decrement by.

Returns (Array)

Returns the new array of numbers.

Example

_.range(4);
// => [0, 1, 2, 3]

_.range(1, 5);
// => [1, 2, 3, 4]

_.range(0, 20, 5);
// => [0, 5, 10, 15]

_.range(0, -4, -1);
// => [0, -1, -2, -3]

_.range(1, 4, 0);
// => [1, 1, 1]

_.range(0);
// => []

runInContext source npm

_.runInContext([context=root])

Create a new pristine lodash function using the given context object.

Arguments

  1. [context=root] (Object)

    The context object.

Returns (Function)

Returns a new lodash function.

Example

_.mixin({ 'foo': _.constant('foo') });

var lodash = _.runInContext();
lodash.mixin({ 'bar': lodash.constant('bar') });

_.isFunction(_.foo);
// => true
_.isFunction(_.bar);
// => false

lodash.isFunction(lodash.foo);
// => false
lodash.isFunction(lodash.bar);
// => true

// using `context` to mock `Date#getTime` use in `_.now`
var mock = _.runInContext({
  'Date': function() {
    return { 'getTime': getTimeMock };
  }
});

// or creating a suped-up `defer` in Node.js
var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;

times source npm

_.times(n, [iteratee=_.identity])

Invokes the iteratee function n times, returning an array of the results of each invocation. The iteratee is invoked with one argument; (index).

Arguments

  1. n (number)

    The number of times to invoke iteratee.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

Returns (Array)

Returns the array of results.

Example

var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
// => [3, 6, 4]

_.times(3, function(n) {
  mage.castSpell(n);
});
// => invokes `mage.castSpell` three times with `n` of `0`, `1`, and `2`

toPath source npm

_.toPath(value)

Converts value to a property path array.

Arguments

  1. value (*)

    The value to convert.

Returns (Array)

Returns the new property path array.

Example

_.toPath('a.b.c');
// => ['a', 'b', 'c']

_.toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']

var path = ['a', 'b', 'c'],
    newPath = _.toPath(path);

console.log(newPath);
// => ['a', 'b', 'c']

console.log(path === newPath);
// => false

uniqueId source npm

_.uniqueId([prefix])

Generates a unique ID. If prefix is provided the ID is appended to it.

Arguments

  1. [prefix] (string)

    The value to prefix the ID with.

Returns (string)

Returns the unique ID.

Example

_.uniqueId('contact_');
// => 'contact_104'

_.uniqueId();
// => '105'