_.compact
_.difference
_.drop
_.first
_.flatten
_.head
_.indexOf
_.initial
_.intersection
_.last
_.lastIndexOf
_.object
_.range
_.rest
_.sortedIndex
_.tail
_.take
_.union
_.uniq
_.unique
_.without
_.zip
_.all
_.any
_.collect
_.contains
_.countBy
_.detect
_.each
_.every
_.filter
_.find
_.foldl
_.foldr
_.forEach
_.groupBy
_.include
_.inject
_.invoke
_.map
_.max
_.min
_.pluck
_.reduce
_.reduceRight
_.reject
_.select
_.shuffle
_.size
_.some
_.sortBy
_.toArray
_.where
_.after
_.bind
_.bindAll
_.bindKey
_.compose
_.debounce
_.defer
_.delay
_.memoize
_.once
_.partial
_.throttle
_.wrap
_.assign
_.clone
_.defaults
_.extend
_.forIn
_.forOwn
_.functions
_.has
_.invert
_.isArguments
_.isArray
_.isBoolean
_.isDate
_.isElement
_.isEmpty
_.isEqual
_.isFinite
_.isFunction
_.isNaN
_.isNull
_.isNumber
_.isObject
_.isPlainObject
_.isRegExp
_.isString
_.isUndefined
_.keys
_.merge
_.methods
_.omit
_.pairs
_.pick
_.values
_.VERSION
_.templateSettings
_.templateSettings.escape
_.templateSettings.evaluate
_.templateSettings.interpolate
_.templateSettings.variable
Creates an array with all falsey values of array
removed. The values false
, null
, 0
, ""
, undefined
and NaN
are all falsey.
array
(Array): The array to compact.
(Array): Returns a new filtered array.
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
Creates an array of array
elements not present in the other arrays using strict equality for comparisons, i.e. ===
.
array
(Array): The array to process.[array1, array2, ...]
(Array): Arrays to check.
(Array): Returns a new array of array
elements not present in the other arrays.
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
// => [1, 3, 4]
Gets the first element of the array
. Pass n
to return the first n
elements of the array
.
head, take
array
(Array): The array to query.[n]
(Number): The number of elements to return.
(Mixed): Returns the first element, or an array of the first n
elements, of array
.
_.first([5, 4, 3, 2, 1]);
// => 5
Flattens a nested array (the nesting can be to any depth). If shallow
is truthy, array
will only be flattened a single level.
array
(Array): The array to compact.shallow
(Boolean): A flag to indicate only flattening a single level.
(Array): Returns a new flattened array.
_.flatten([1, [2], [3, [[4]]]]);
// => [1, 2, 3, 4];
_.flatten([1, [2], [3, [[4]]]], true);
// => [1, 2, 3, [[4]]];
Gets the index at which the first occurrence of value
is found using strict equality for comparisons, i.e. ===
. If the array
is already sorted, passing true
for fromIndex
will run a faster binary search.
array
(Array): The array to search.value
(Mixed): The value to search for.[fromIndex=0]
(Boolean|Number): The index to search from ortrue
to perform a binary search on a sortedarray
.
(Number): Returns the index of the matched value or -1
.
_.indexOf([1, 2, 3, 1, 2, 3], 2);
// => 1
_.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
// => 4
_.indexOf([1, 1, 2, 2, 3, 3], 2, true);
// => 2
Gets all but the last element of array
. Pass n
to exclude the last n
elements from the result.
array
(Array): The array to query.[n=1]
(Number): The number of elements to exclude.
(Array): Returns all but the last element, or n
elements, of array
.
_.initial([3, 2, 1]);
// => [3, 2]
Computes the intersection of all the passed-in arrays using strict equality for comparisons, i.e. ===
.
[array1, array2, ...]
(Array): Arrays to process.
(Array): Returns a new array of unique elements, in order, that are present in all of the arrays.
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
// => [1, 2]
Gets the last element of the array
. Pass n
to return the last n
elements of the array
.
array
(Array): The array to query.[n]
(Number): The number of elements to return.
(Mixed): Returns the last element, or an array of the last n
elements, of array
.
_.last([3, 2, 1]);
// => 1
Gets the index at which the last occurrence of value
is found using strict equality for comparisons, i.e. ===
. If fromIndex
is negative, it is used as the offset from the end of the collection.
array
(Array): The array to search.value
(Mixed): The value to search for.[fromIndex=array.length-1]
(Number): The index to search from.
(Number): Returns the index of the matched value or -1
.
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
// => 4
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
// => 1
Creates an object composed from arrays of keys
and values
. Pass either a single two dimensional array, i.e. [[key1, value1], [key2, value2]]
, or two arrays, one of keys
and one of corresponding values
.
keys
(Array): The array of keys.[values=[]]
(Array): The array of values.
(Object): Returns an object composed of the given keys and corresponding values.
_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
// => { 'moe': 30, 'larry': 40, 'curly': 50 }
Creates an array of numbers (positive and/or negative) progressing from start
up to but not including stop
. This method is a port of Python's range()
function. See http://docs.python.org/library/functions.html#range.
[start=0]
(Number): The start of the range.end
(Number): The end of the range.[step=1]
(Number): The value to increment or descrement by.
(Array): Returns a new range array.
_.range(10);
// => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
// => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
// => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
// => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0);
// => []
The opposite of _.initial
, this method gets all but the first value of array
. Pass n
to exclude the first n
values from the result.
drop, tail
array
(Array): The array to query.[n=1]
(Number): The number of elements to exclude.
(Array): Returns all but the first element, or n
elements, of array
.
_.rest([3, 2, 1]);
// => [2, 1]
Uses a binary search to determine the smallest index at which the value
should be inserted into array
in order to maintain the sort order of the sorted array
. If callback
is passed, it will be executed for value
and each element in array
to compute their sort ranking. The callback
is bound to thisArg
and invoked with one argument; (value). The callback
argument may also be the name of a property to order by.
array
(Array): The array to iterate over.value
(Mixed): The value to evaluate.[callback=identity|property]
(Function|String): The function called per iteration or property name to order by.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Number): Returns the index at which the value should be inserted into array
.
_.sortedIndex([20, 30, 50], 40);
// => 2
_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
// => 2
var dict = {
'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
};
_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return dict.wordToNumber[word];
});
// => 2
_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return this.wordToNumber[word];
}, dict);
// => 2
Computes the union of the passed-in arrays using strict equality for comparisons, i.e. ===
.
[array1, array2, ...]
(Array): Arrays to process.
(Array): Returns a new array of unique values, in order, that are present in one or more of the arrays.
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
// => [1, 2, 3, 101, 10]
Creates a duplicate-value-free version of the array
using strict equality for comparisons, i.e. ===
. If the array
is already sorted, passing true
for isSorted
will run a faster algorithm. If callback
is passed, each element of array
is passed through a callbackbefore uniqueness is computed. The
callbackis bound to
thisArg` and invoked with three arguments; (value, index, array).
unique
array
(Array): The array to process.[isSorted=false]
(Boolean): A flag to indicate that thearray
is already sorted.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Array): Returns a duplicate-value-free array.
_.uniq([1, 2, 1, 3, 1]);
// => [1, 2, 3]
_.uniq([1, 1, 2, 2, 3], true);
// => [1, 2, 3]
_.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); });
// => [1, 2, 3]
_.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math);
// => [1, 2, 3]
Creates an array with all occurrences of the passed values removed using strict equality for comparisons, i.e. ===
.
array
(Array): The array to filter.[value1, value2, ...]
(Mixed): Values to remove.
(Array): Returns a new filtered array.
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
// => [2, 3, 4]
Groups the elements of each array at their corresponding indexes. Useful for separate data sources that are coordinated through matching array indexes. For a matrix of nested arrays, _.zip.apply(...)
can transpose the matrix in a similar fashion.
[array1, array2, ...]
(Array): Arrays to process.
(Array): Returns a new array of grouped elements.
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
// => [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]]
The lodash
function.
value
(Mixed): The value to wrap in alodash
instance.
(Object): Returns a lodash
instance.
Wraps the value in a lodash
wrapper object.
value
(Mixed): The value to wrap.
(Object): Returns the wrapper object.
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 },
{ 'name': 'curly', 'age': 60 }
];
var youngest = _.chain(stooges)
.sortBy(function(stooge) { return stooge.age; })
.map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
.first();
// => 'moe is 40'
Invokes interceptor
with the value
as the first argument, and then returns value
. The purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
value
(Mixed): The value to pass tointerceptor
.interceptor
(Function): The function to invoke.
(Mixed): Returns value
.
_.chain([1, 2, 3, 200])
.filter(function(num) { return num % 2 == 0; })
.tap(alert)
.map(function(num) { return num * num; })
.value();
// => // [2, 200] (alerted)
// => [4, 40000]
This function returns the wrapper object. Note: This function is defined to ensure the existing wrapper object is returned, instead of creating a new wrapper object like the _.chain
method does.
(Mixed): Returns the wrapper object.
var wrapped = _([1, 2, 3]);
wrapped === wrapped.chain();
// => true
Produces the toString
result of the wrapped value.
(String): Returns the string result.
_([1, 2, 3]).toString();
// => '1,2,3'
Extracts the wrapped value.
value
(Mixed): Returns the wrapped value.
_([1, 2, 3]).valueOf();
// => [1, 2, 3]
Checks if a given target
element is present in a collection
using strict equality for comparisons, i.e. ===
. If fromIndex
is negative, it is used as the offset from the end of the collection.
include
collection
(Array|Object|String): The collection to iterate over.target
(Mixed): The value to check for.[fromIndex=0]
(Number): The index to search from.
(Boolean): Returns true
if the target
element is found, else false
.
_.contains([1, 2, 3], 1);
// => true
_.contains([1, 2, 3], 1, 2);
// => false
_.contains({ 'name': 'moe', 'age': 40 }, 'moe');
// => true
_.contains('curly', 'ur');
// => true
Creates an object composed of keys returned from running each element of collection
through a callback
. The corresponding value of each key is the number of times the key was returned by callback
. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection). The callback
argument may also be the name of a property to count by (e.g. 'length').
collection
(Array|Object|String): The collection to iterate over.callback|property
(Function|String): The function called per iteration or property name to count by.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Object): Returns the composed aggregate object.
_.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
// => { '4': 1, '6': 2 }
_.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
// => { '4': 1, '6': 2 }
_.countBy(['one', 'two', 'three'], 'length');
// => { '3': 2, '5': 1 }
Checks if the callback
returns a truthy value for all elements of a collection
. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
all
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Boolean): Returns true
if all elements pass the callback check, else false
.
_.every([true, 1, null, 'yes'], Boolean);
// => false
Examines each element in a collection
, returning an array of all elements the callback
returns truthy for. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
select
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Array): Returns a new array of elements that passed the callback check.
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
// => [2, 4, 6]
Examines each element in a collection
, returning the first one the callback
returns truthy for. The function returns as soon as it finds an acceptable element, and does not iterate over the entire collection
. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
detect
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Mixed): Returns the element that passed the callback check, else undefined
.
var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
// => 2
Iterates over a collection
, executing the callback
for each element in the collection
. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection). Callbacks may exit iteration early by explicitly returning false
.
each
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Array, Object, String): Returns collection
.
_([1, 2, 3]).forEach(alert).join(',');
// => alerts each number and returns '1,2,3'
_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
// => alerts each number value (order is not guaranteed)
Creates an object composed of keys returned from running each element of collection
through a callback
. The corresponding value of each key is an array of elements passed to callback
that returned the key. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection). The callback
argument may also be the name of a property to group by (e.g. 'length').
collection
(Array|Object|String): The collection to iterate over.callback|property
(Function|String): The function called per iteration or property name to group by.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Object): Returns the composed aggregate object.
_.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
// => { '4': [4.2], '6': [6.1, 6.4] }
_.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
// => { '4': [4.2], '6': [6.1, 6.4] }
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }
Invokes the method named by methodName
on each element in the collection
, returning an array of the results of each invoked method. Additional arguments will be passed to each invoked method. If methodName
is a function it will be invoked for, and this
bound to, each element in the collection
.
collection
(Array|Object|String): The collection to iterate over.methodName
(Function|String): The name of the method to invoke or the function invoked per iteration.[arg1, arg2, ...]
(Mixed): Arguments to invoke the method with.
(Array): Returns a new array of the results of each invoked method.
_.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']]
Creates an array of values by running each element in the collection
through a callback
. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
collect
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Array): Returns a new array of the results of each callback
execution.
_.map([1, 2, 3], function(num) { return num * 3; });
// => [3, 6, 9]
_.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
// => [3, 6, 9] (order is not guaranteed)
Retrieves the maximum value of an array
. If callback
is passed, it will be executed for each value in the array
to generate the criterion by which the value is ranked. The callback
is bound to thisArg
and invoked with three arguments; (value, index, collection).
collection
(Array|Object|String): The collection to iterate over.[callback]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Mixed): Returns the maximum value.
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 },
{ 'name': 'curly', 'age': 60 }
];
_.max(stooges, function(stooge) { return stooge.age; });
// => { 'name': 'curly', 'age': 60 };
Retrieves the minimum value of an array
. If callback
is passed, it will be executed for each value in the array
to generate the criterion by which the value is ranked. The callback
is bound to thisArg
and invoked with three arguments; (value, index, collection).
collection
(Array|Object|String): The collection to iterate over.[callback]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Mixed): Returns the minimum value.
_.min([10, 5, 100, 2, 1000]);
// => 2
Retrieves the value of a specified property from all elements in the collection
.
collection
(Array|Object|String): The collection to iterate over.property
(String): The property to pluck.
(Array): Returns a new array of property values.
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 },
{ 'name': 'curly', 'age': 60 }
];
_.pluck(stooges, 'name');
// => ['moe', 'larry', 'curly']
Boils down a collection
to a single value. The initial state of the reduction is accumulator
and each successive step of it should be returned by the callback
. The callback
is bound to thisArg
and invoked with 4
arguments; for arrays they are (accumulator, value, index|key, collection).
foldl, inject
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[accumulator]
(Mixed): Initial value of the accumulator.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Mixed): Returns the accumulated value.
var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; });
// => 6
The right-associative version of _.reduce
.
foldr
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[accumulator]
(Mixed): Initial value of the accumulator.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Mixed): Returns the accumulated value.
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
// => [4, 5, 2, 3, 0, 1]
The opposite of _.filter
, this method returns the values of a collection
that callback
does not return truthy for.
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Array): Returns a new array of elements that did not pass the callback check.
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
// => [1, 3, 5]
Creates an array of shuffled array
values, using a version of the Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
collection
(Array|Object|String): The collection to shuffle.
(Array): Returns a new shuffled collection.
_.shuffle([1, 2, 3, 4, 5, 6]);
// => [4, 1, 6, 3, 5, 2]
Gets the size of the collection
by returning collection.length
for arrays and array-like objects or the number of own enumerable properties for objects.
collection
(Array|Object|String): The collection to inspect.
(Number): Returns collection.length
or number of own enumerable properties.
_.size([1, 2]);
// => 2
_.size({ 'one': 1, 'two': 2, 'three': 3 });
// => 3
_.size('curly');
// => 5
Checks if the callback
returns a truthy value for any element of a collection
. The function returns as soon as it finds passing value, and does not iterate over the entire collection
. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
any
collection
(Array|Object|String): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Boolean): Returns true
if any element passes the callback check, else false
.
_.some([null, 0, 'yes', false], Boolean);
// => true
Creates an array, stable sorted in ascending order by the results of running each element of collection
through a callback
. The callback
is bound to thisArg
and invoked with three arguments; (value, index|key, collection). The callback
argument may also be the name of a property to sort by (e.g. 'length').
collection
(Array|Object|String): The collection to iterate over.callback|property
(Function|String): The function called per iteration or property name to sort by.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Array): Returns a new array of sorted elements.
_.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
// => [3, 1, 2]
_.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
// => [3, 1, 2]
_.sortBy(['larry', 'brendan', 'moe'], 'length');
// => ['moe', 'larry', 'brendan']
Converts the collection
to an array.
collection
(Array|Object|String): The collection to convert.
(Array): Returns the new converted array.
(function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
// => [2, 3, 4]
Examines each element in a collection
, returning an array of all elements that contain the given properties
.
collection
(Array|Object|String): The collection to iterate over.properties
(Object): The object of property values to filter by.
(Array): Returns a new array of elements that contain the given properties
.
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 },
{ 'name': 'curly', 'age': 60 }
];
_.where(stooges, { 'age': 40 });
// => [{ 'name': 'moe', 'age': 40 }]
Creates a function that is restricted to executing func
only after it is called n
times. The func
is executed with the this
binding of the created function.
n
(Number): The number of times the function must be called before it is executed.func
(Function): The function to restrict.
(Function): Returns the new restricted function.
var renderNotes = _.after(notes.length, render);
_.forEach(notes, function(note) {
note.asyncSave({ 'success': renderNotes });
});
// `renderNotes` is run once, after all notes have saved
Creates a function that, when called, invokes func
with the this
binding of thisArg
and prepends any additional bind
arguments to those passed to the bound function.
func
(Function): The function to bind.[thisArg]
(Mixed): Thethis
binding offunc
.[arg1, arg2, ...]
(Mixed): Arguments to be partially applied.
(Function): Returns the new bound function.
var func = function(greeting) {
return greeting + ' ' + this.name;
};
func = _.bind(func, { 'name': 'moe' }, 'hi');
func();
// => 'hi moe'
Binds methods on object
to object
, overwriting the existing method. If no method names are provided, all the function properties of object
will be bound.
object
(Object): The object to bind and assign the bound methods to.[methodName1, methodName2, ...]
(String): Method names on the object to bind.
(Object): Returns object
.
var buttonView = {
'label': 'lodash',
'onClick': function() { alert('clicked: ' + this.label); }
};
_.bindAll(buttonView);
jQuery('#lodash_button').on('click', buttonView.onClick);
// => When the button is clicked, `this.label` will have the correct value
Creates a function that, when called, invokes the method at object[key]
and prepends any additional bindKey
arguments to those passed to the bound function. This method differs from _.bind
by allowing bound functions to reference methods that will be redefined or don't yet exist. See http://michaux.ca/articles/lazy-function-definition-pattern.
object
(Object): The object the method belongs to.key
(String): The key of the method.[arg1, arg2, ...]
(Mixed): Arguments to be partially applied.
(Function): Returns the new bound function.
var object = {
'name': 'moe',
'greet': function(greeting) {
return greeting + ' ' + this.name;
}
};
var func = _.bindKey(object, 'greet', 'hi');
func();
// => 'hi moe'
object.greet = function(greeting) {
return greeting + ', ' + this.name + '!';
};
func();
// => 'hi, moe!'
Creates a function that is the composition of the passed functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f()
, g()
, and h()
produces f(g(h()))
. Each function is executed with the this
binding of the composed function.
[func1, func2, ...]
(Function): Functions to compose.
(Function): Returns the new composed function.
var greet = function(name) { return 'hi: ' + name; };
var exclaim = function(statement) { return statement + '!'; };
var welcome = _.compose(exclaim, greet);
welcome('moe');
// => 'hi: moe!'
Creates a function that will delay the execution of func
until after wait
milliseconds have elapsed since the last time it was invoked. Pass true
for immediate
to cause debounce to invoke func
on the leading, instead of the trailing, edge of the wait
timeout. Subsequent calls to the debounced function will return the result of the last func
call.
func
(Function): The function to debounce.wait
(Number): The number of milliseconds to delay.immediate
(Boolean): A flag to indicate execution is on the leading edge of the timeout.
(Function): Returns the new debounced function.
var lazyLayout = _.debounce(calculateLayout, 300);
jQuery(window).on('resize', lazyLayout);
Defers executing the func
function until the current call stack has cleared. Additional arguments will be passed to func
when it is invoked.
func
(Function): The function to defer.[arg1, arg2, ...]
(Mixed): Arguments to invoke the function with.
(Number): Returns the setTimeout
timeout id.
_.defer(function() { alert('deferred'); });
// returns from the function before `alert` is called
Executes the func
function after wait
milliseconds. Additional arguments will be passed to func
when it is invoked.
func
(Function): The function to delay.wait
(Number): The number of milliseconds to delay execution.[arg1, arg2, ...]
(Mixed): Arguments to invoke the function with.
(Number): Returns the setTimeout
timeout id.
var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
// => 'logged later' (Appears after one second.)
Creates a function that memoizes the result of func
. If resolver
is passed, it will be used to determine the cache key for storing the result based on the arguments passed to the memoized function. By default, the first argument passed to the memoized function is used as the cache key. The func
is executed with the this
binding of the memoized function.
func
(Function): The function to have its output memoized.[resolver]
(Function): A function used to resolve the cache key.
(Function): Returns the new memoizing function.
var fibonacci = _.memoize(function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
Creates a function that is restricted to execute func
once. Repeat calls to the function will return the value of the first call. The func
is executed with the this
binding of the created function.
func
(Function): The function to restrict.
(Function): Returns the new restricted function.
var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.
Creates a function that, when called, invokes func
with any additional partial
arguments prepended to those passed to the new function. This method is similar to bind
, except it does not alter the this
binding.
func
(Function): The function to partially apply arguments to.[arg1, arg2, ...]
(Mixed): Arguments to be partially applied.
(Function): Returns the new partially applied function.
var greet = function(greeting, name) { return greeting + ': ' + name; };
var hi = _.partial(greet, 'hi');
hi('moe');
// => 'hi: moe'
Creates a function that, when executed, will only call the func
function at most once per every wait
milliseconds. If the throttled function is invoked more than once during the wait
timeout, func
will also be called on the trailing edge of the timeout. Subsequent calls to the throttled function will return the result of the last func
call.
func
(Function): The function to throttle.wait
(Number): The number of milliseconds to throttle executions to.
(Function): Returns the new throttled function.
var throttled = _.throttle(updatePosition, 100);
jQuery(window).on('scroll', throttled);
Creates a function that passes value
to the wrapper
function as its first argument. Additional arguments passed to the function are appended to those passed to the wrapper
function. The wrapper
is executed with the this
binding of the created function.
value
(Mixed): The value to wrap.wrapper
(Function): The wrapper function.
(Function): Returns the new function.
var hello = function(name) { return 'hello ' + name; };
hello = _.wrap(hello, function(func) {
return 'before, ' + func('moe') + ', after';
});
hello();
// => 'before, hello moe, after'
Assigns own enumerable properties of source object(s) to the destination
object. Subsequent sources will overwrite propery assignments of previous sources.
extend
object
(Object): The destination object.[source1, source2, ...]
(Object): The source objects.
(Object): Returns the destination object.
_.assign({ 'name': 'moe' }, { 'age': 40 });
// => { 'name': 'moe', 'age': 40 }
Creates a clone of value
. If deep
is true
, all nested objects will also be cloned, otherwise they will be assigned by reference. Functions and DOM nodes are not cloned. The enumerable properties of arguments
objects and objects created by constructors other than Object
are cloned to plain Object
objects. Note: Lo-Dash's deep clone functionality is loosely based on the structured clone algorithm. See http://www.w3.org/TR/html5/common-dom-interfaces.html#internal-structured-cloning-algorithm.
value
(Mixed): The value to clone.deep
(Boolean): A flag to indicate a deep clone.
(Mixed): Returns the cloned value
.
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 },
{ 'name': 'curly', 'age': 60 }
];
_.clone({ 'name': 'moe' });
// => { 'name': 'moe' }
var shallow = _.clone(stooges);
shallow[0] === stooges[0];
// => true
var deep = _.clone(stooges, true);
deep[0] === stooges[0];
// => false
Assigns own enumerable properties of source object(s) to the destination
object for all destination
properties that resolve to null
/undefined
. Once a property is set, additional defaults of the same property will be ignored.
object
(Object): The destination object.[default1, default2, ...]
(Object): The default objects.
(Object): Returns the destination object.
var iceCream = { 'flavor': 'chocolate' };
_.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' });
// => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' }
Iterates over object
's own and inherited enumerable properties, executing the callback
for each property. The callback
is bound to thisArg
and invoked with three arguments; (value, key, object). Callbacks may exit iteration early by explicitly returning false
.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Object): Returns object
.
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function() {
alert('Woof, woof!');
};
_.forIn(new Dog('Dagny'), function(value, key) {
alert(key);
});
// => alerts 'name' and 'bark' (order is not guaranteed)
Iterates over an object's own enumerable properties, executing the callback
for each property. The callback
is bound to thisArg
and invoked with three arguments; (value, key, object). Callbacks may exit iteration early by explicitly returning false
.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Object): Returns object
.
_.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
alert(key);
});
// => alerts '0', '1', and 'length' (order is not guaranteed)
Creates a sorted array of all enumerable properties, own and inherited, of object
that have function values.
methods
object
(Object): The object to inspect.
(Array): Returns a new array of property names that have function values.
_.functions(_);
// => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
Checks if the specified object property
exists and is a direct property, instead of an inherited property.
object
(Object): The object to check.property
(String): The property to check for.
(Boolean): Returns true
if key is a direct property, else false
.
_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
// => true
Creates an object composed of the inverted keys and values of the given object
.
object
(Object): The object to invert.
(Object): Returns the created inverted object.
_.invert({ 'first': 'Moe', 'second': 'Larry', 'third': 'Curly' });
// => { 'Moe': 'first', 'Larry': 'second', 'Curly': 'third' } (order is not guaranteed)
Checks if value
is an arguments
object.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is an arguments
object, else false
.
(function() { return _.isArguments(arguments); })(1, 2, 3);
// => true
_.isArguments([1, 2, 3]);
// => false
Checks if value
is an array.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is an array, else false
.
(function() { return _.isArray(arguments); })();
// => false
_.isArray([1, 2, 3]);
// => true
Checks if value
is a boolean (true
or false
) value.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a boolean value, else false
.
_.isBoolean(null);
// => false
Checks if value
is a date.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a date, else false
.
_.isDate(new Date);
// => true
Checks if value
is a DOM element.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a DOM element, else false
.
_.isElement(document.body);
// => true
Checks if value
is empty. Arrays, strings, or arguments
objects with a length of 0
and objects with no own enumerable properties are considered "empty".
value
(Array|Object|String): The value to inspect.
(Boolean): Returns true
if the value
is empty, else false
.
_.isEmpty([1, 2, 3]);
// => false
_.isEmpty({});
// => true
_.isEmpty('');
// => true
Performs a deep comparison between two values to determine if they are equivalent to each other.
a
(Mixed): The value to compare.b
(Mixed): The other value to compare.
(Boolean): Returns true
if the values are equvalent, else false
.
var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
moe == clone;
// => false
_.isEqual(moe, clone);
// => true
Checks if value
is, or can be coerced to, a finite number. Note: This is not the same as native isFinite
, which will return true for booleans and empty strings. See http://es5.github.com/#x15.1.2.5.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a finite number, else false
.
_.isFinite(-101);
// => true
_.isFinite('10');
// => true
_.isFinite(true);
// => false
_.isFinite('');
// => false
_.isFinite(Infinity);
// => false
Checks if value
is a function.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a function, else false
.
_.isFunction(_);
// => true
Checks if value
is NaN
. Note: This is not the same as native isNaN
, which will return true
for undefined
and other values. See http://es5.github.com/#x15.1.2.4.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is NaN
, else false
.
_.isNaN(NaN);
// => true
_.isNaN(new Number(NaN));
// => true
isNaN(undefined);
// => true
_.isNaN(undefined);
// => false
Checks if value
is null
.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is null
, else false
.
_.isNull(null);
// => true
_.isNull(undefined);
// => false
Checks if value
is a number.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a number, else false
.
_.isNumber(8.4 * 5);
// => true
Checks if value
is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0)
, and new String('')
)
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is an object, else false
.
_.isObject({});
// => true
_.isObject([1, 2, 3]);
// => true
_.isObject(1);
// => false
Checks if a given value
is an object created by the Object
constructor.
value
(Mixed): The value to check.
(Boolean): Returns true
if value
is a plain object, else false
.
function Stooge(name, age) {
this.name = name;
this.age = age;
}
_.isPlainObject(new Stooge('moe', 40));
// => false
_.isPlainObject([1, 2, 3]);
// => false
_.isPlainObject({ 'name': 'moe', 'age': 40 });
// => true
Checks if value
is a regular expression.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a regular expression, else false
.
_.isRegExp(/moe/);
// => true
Checks if value
is a string.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is a string, else false
.
_.isString('moe');
// => true
Checks if value
is undefined
.
value
(Mixed): The value to check.
(Boolean): Returns true
if the value
is undefined
, else false
.
_.isUndefined(void 0);
// => true
Creates an array composed of the own enumerable property names of object
.
object
(Object): The object to inspect.
(Array): Returns a new array of property names.
_.keys({ 'one': 1, 'two': 2, 'three': 3 });
// => ['one', 'two', 'three'] (order is not guaranteed)
Merges enumerable properties of the source object(s) into the destination
object. Subsequent sources will overwrite propery assignments of previous sources.
object
(Object): The destination object.[source1, source2, ...]
(Object): The source objects.
(Object): Returns the destination object.
var stooges = [
{ 'name': 'moe' },
{ 'name': 'larry' }
];
var ages = [
{ 'age': 40 },
{ 'age': 50 }
];
_.merge(stooges, ages);
// => [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }]
Creates a shallow clone of object
excluding the specified properties. Property names may be specified as individual arguments or as arrays of property names. If callback
is passed, it will be executed for each property in the object
, omitting the properties callback
returns truthy for. The callback
is bound to thisArg
and invoked with three arguments; (value, key, object).
object
(Object): The source object.callback|[prop1, prop2, ...]
(Function|String): The properties to omit or the function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Object): Returns an object without the omitted properties.
_.omit({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid');
// => { 'name': 'moe', 'age': 40 }
_.omit({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
return key.charAt(0) == '_';
});
// => { 'name': 'moe' }
Creates a two dimensional array of the given object's key-value pairs, i.e. [[key1, value1], [key2, value2]]
.
object
(Object): The object to inspect.
(Array): Returns new array of key-value pairs.
_.pairs({ 'moe': 30, 'larry': 40, 'curly': 50 });
// => [['moe', 30], ['larry', 40], ['curly', 50]] (order is not guaranteed)
Creates a shallow clone of object
composed of the specified properties. Property names may be specified as individual arguments or as arrays of property names. If callback
is passed, it will be executed for each property in the object
, picking the properties callback
returns truthy for. The callback
is bound to thisArg
and invoked with three arguments; (value, key, object).
object
(Object): The source object.callback|[prop1, prop2, ...]
(Function|String): The properties to pick or the function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Object): Returns an object composed of the picked properties.
_.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age');
// => { 'name': 'moe', 'age': 40 }
_.pick({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
return key.charAt(0) != '_';
});
// => { 'name': 'moe' }
Creates an array composed of the own enumerable property values of object
.
object
(Object): The object to inspect.
(Array): Returns a new array of property values.
_.values({ 'one': 1, 'two': 2, 'three': 3 });
// => [1, 2, 3]
Converts the characters &
, <
, >
, "
, and '
in string
to their corresponding HTML entities.
string
(String): The string to escape.
(String): Returns the escaped string.
_.escape('Moe, Larry & Curly');
// => 'Moe, Larry & Curly'
This function returns the first argument passed to it. Note: This function is used throughout Lo-Dash as a default callback.
value
(Mixed): Any value.
(Mixed): Returns value
.
var moe = { 'name': 'moe' };
moe === _.identity(moe);
// => true
Adds functions properties of object
to the lodash
function and chainable wrapper.
object
(Object): The object of function properties to add tolodash
.
_.mixin({
'capitalize': function(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
});
_.capitalize('larry');
// => 'Larry'
_('curly').capitalize();
// => 'Curly'
Reverts the '_' variable to its previous value and returns a reference to the lodash
function.
(Function): Returns the lodash
function.
var lodash = _.noConflict();
Produces a random number between min
and max
(inclusive). If only one argument is passed, a number between 0
and the given number will be returned.
[min=0]
(Number): The minimum possible value.[max=1]
(Number): The maximum possible value.
(Number): Returns a random number.
_.random(0, 5);
// => a number between 1 and 5
_.random(5);
// => also a number between 1 and 5
Resolves the value of property
on object
. If property
is a function it will be invoked and its result returned, else the property value is returned. If object
is falsey, then null
is returned.
object
(Object): The object to inspect.property
(String): The property to get the value of.
(Mixed): Returns the resolved value.
var object = {
'cheese': 'crumpets',
'stuff': function() {
return 'nonsense';
}
};
_.result(object, 'cheese');
// => 'crumpets'
_.result(object, 'stuff');
// => 'nonsense'
A micro-templating method that handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. Note: In the development build _.template
utilizes sourceURLs for easier debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl Note: Lo-Dash may be used in Chrome extensions by either creating a lodash csp
build and avoiding _.template
use, or loading Lo-Dash in a sandboxed page. See http://developer.chrome.com/trunk/extensions/sandboxingEval.html
text
(String): The template text.data
(Obect): The data object used to populate the text.options
(Object): The options object. escape - The "escape" delimiter regexp. evaluate - The "evaluate" delimiter regexp. interpolate - The "interpolate" delimiter regexp. sourceURL - The sourceURL of the template's compiled source. variable - The data object variable name.
(Function, String): Returns a compiled function when no data
object is given, else it returns the interpolated text.
// using a compiled template
var compiled = _.template('hello <%= name %>');
compiled({ 'name': 'moe' });
// => 'hello moe'
var list = '<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>';
_.template(list, { 'people': ['moe', 'larry', 'curly'] });
// => '<li>moe</li><li>larry</li><li>curly</li>'
// using the "escape" delimiter to escape HTML in data property values
_.template('<b><%- value %></b>', { 'value': '<script>' });
// => '<b><script></b>'
// using the ES6 delimiter as an alternative to the default "interpolate" delimiter
_.template('hello ${ name }', { 'name': 'curly' });
// => 'hello curly'
// using the internal `print` function in "evaluate" delimiters
_.template('<% print("hello " + epithet); %>!', { 'epithet': 'stooge' });
// => 'hello stooge!'
// using custom template delimiters
_.templateSettings = {
'interpolate': /{{([\s\S]+?)}}/g
};
_.template('hello {{ name }}!', { 'name': 'mustache' });
// => 'hello mustache!'
// using the `sourceURL` option to specify a custom sourceURL for the template
var compiled = _.template('hello <%= name %>', null, { '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('hello <%= data.name %>!', null, { 'variable': 'data' });
compiled.source;
// => function(data) {
var __t, __p = '', __e = _.escape;
__p += 'hello ' + ((__t = ( data.name )) == 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 + '\
};\
');
Executes the callback
function n
times, returning an array of the results of each callback
execution. The callback
is bound to thisArg
and invoked with one argument; (index).
n
(Number): The number of times to execute the callback.callback
(Function): The function called per iteration.[thisArg]
(Mixed): Thethis
binding ofcallback
.
(Array): Returns a new array of the results of each callback
execution.
var diceRolls = _.times(3, _.partial(_.random, 1, 6));
// => [3, 6, 4]
_.times(3, function(n) { mage.castSpell(n); });
// => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
_.times(3, function(n) { this.cast(n); }, mage);
// => also calls `mage.castSpell(n)` three times
The opposite of _.escape
, this method converts the HTML entities &
, <
, >
, "
, and '
in string
to their corresponding characters.
string
(String): The string to unescape.
(String): Returns the unescaped string.
_.unescape('Moe, Larry & Curly');
// => 'Moe, Larry & Curly'
Generates a unique ID. If prefix
is passed, the ID will be appended to it.
[prefix]
(String): The value to prefix the ID with.
(String): Returns the unique ID.
_.uniqueId('contact_');
// => 'contact_104'
_.uniqueId();
// => '105'
(String): The semantic version number.
(Object): By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby (ERB). Change the following template settings to use alternative delimiters.
(RegExp): Used to detect data
property values to be HTML-escaped.
(RegExp): Used to detect code to be evaluated.
(RegExp): Used to detect data
property values to inject.
(String): Used to reference the data object in the template text.