Lo-Dash v2.4.1
_.compact
_.difference
_.drop
->rest
_.findIndex
_.findLastIndex
_.first
_.flatten
_.head
->first
_.indexOf
_.initial
_.intersection
_.last
_.lastIndexOf
_.object
->zipObject
_.pull
_.range
_.remove
_.rest
_.slice
_.sortedIndex
_.tail
->rest
_.take
->first
_.union
_.uniq
_.unique
->uniq
_.unzip
->zip
_.without
_.xor
_.zip
_.zipObject
_
_.chain
_.tap
_.prototype.chain
_.prototype.toString
_.prototype.value
->valueOf
_.prototype.valueOf
_.all
->every
_.any
->some
_.at
_.collect
->map
_.contains
_.countBy
_.detect
->find
_.each
->forEach
_.eachRight
->forEachRight
_.every
_.filter
_.find
_.findLast
_.findWhere
->find
_.foldl
->reduce
_.foldr
->reduceRight
_.forEach
_.forEachRight
_.groupBy
_.include
->contains
_.indexBy
_.inject
->reduce
_.invoke
_.map
_.max
_.min
_.partition
_.pluck
_.reduce
_.reduceRight
_.reject
_.sample
_.select
->filter
_.shuffle
_.size
_.some
_.sortBy
_.toArray
_.where
_.after
_.bind
_.bindAll
_.bindKey
_.compose
_.curry
_.debounce
_.defer
_.delay
_.memoize
_.once
_.partial
_.partialRight
_.throttle
_.wrap
_.assign
_.clone
_.cloneDeep
_.create
_.defaults
_.extend
->assign
_.findKey
_.findLastKey
_.forIn
_.forInRight
_.forOwn
_.forOwnRight
_.functions
_.has
_.invert
_.isArguments
_.isArray
_.isBoolean
_.isDate
_.isElement
_.isEmpty
_.isEqual
_.isFinite
_.isFunction
_.isNaN
_.isNull
_.isNumber
_.isObject
_.isPlainObject
_.isRegExp
_.isString
_.isUndefined
_.keys
_.mapValues
_.merge
_.methods
->functions
_.omit
_.pairs
_.pick
_.transform
_.values
_.now
_.callback
->createCallback
_.constant
_.createCallback
_.identity
_.matches
_.mixin
_.noConflict
_.noop
_.parseInt
_.property
_.random
_.result
_.runInContext
_.times
_.uniqueId
_.VERSION
_.support
_.support.argsClass
_.support.argsObject
_.support.enumErrorProps
_.support.enumPrototypes
_.support.funcDecomp
_.support.funcNames
_.support.nonEnumArgs
_.support.nonEnumShadows
_.support.ownLast
_.support.spliceObjects
_.support.unindexedChars
_.templateSettings
_.templateSettings.escape
_.templateSettings.evaluate
_.templateSettings.interpolate
_.templateSettings.variable
_.templateSettings.imports
Creates an array with all falsey values removed. The values false
, null
, 0
, ""
, undefined
, and NaN
are all falsey.
array
(Array): The array to compact.
(Array): Returns a new array of filtered values.
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
Creates an array excluding all values of the provided arrays using strict equality for comparisons, i.e. ===
.
array
(Array): The array to process.[values]
(...Array): The arrays of values to exclude.
(Array): Returns a new array of filtered values.
_.difference([1, 2, 3], [5, 2, 10]);
// => [1, 3]
This method is like _.find
except that it returns the index of the first element that passes the callback check, instead of the element itself.
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(number): Returns the index of the found element, else -1
.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40, 'blocked': true },
{ 'name': 'pebbles', 'age': 1 }
];
_.findIndex(characters, function(chr) {
return chr.age < 20;
});
// => 2
// using "_.where" callback shorthand
_.findIndex(characters, { 'age': 36 });
// => 0
// using "_.pluck" callback shorthand
_.findIndex(characters, 'blocked');
// => 1
This method is like _.findIndex
except that it iterates over elements of a collection
from right to left.
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(number): Returns the index of the found element, else -1
.
var characters = [
{ 'name': 'barney', 'age': 36, 'blocked': true },
{ 'name': 'fred', 'age': 40 },
{ 'name': 'pebbles', 'age': 1, 'blocked': true }
];
_.findLastIndex(characters, function(chr) {
return chr.age > 30;
});
// => 1
// using "_.where" callback shorthand
_.findLastIndex(characters, { 'age': 36 });
// => 0
// using "_.pluck" callback shorthand
_.findLastIndex(characters, 'blocked');
// => 2
Gets the first element or first n
elements of an array. If a callback is provided elements at the beginning of the array are returned as long as the callback returns truey. The callback is bound to thisArg
and invoked with three arguments; (value, index, array).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.head, _.take
array
(Array): The array to query.[callback]
(Function|Object|number|string): The function called per element or the number of elements to return. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the first element(s) of array
.
_.first([1, 2, 3]);
// => 1
// returns the first two elements
_.first([1, 2, 3], 2);
// => [1, 2]
// returns elements from the beginning until the callback result is falsey
_.first([1, 2, 3], function(num) {
return num < 3;
});
// => [1, 2]
var characters = [
{ 'name': 'barney', 'employer': 'slate', 'blocked': true },
{ 'name': 'fred', 'employer': 'slate' },
{ 'name': 'pebbles', 'employer': 'na', 'blocked': true }
];
// using "_.pluck" callback shorthand
_.first(characters, 'blocked');
// => [{ 'name': 'barney', 'employer': 'slate', 'blocked': true }]
// using "_.where" callback shorthand
_.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
// => ['barney', 'fred']
Flattens a nested array (the nesting can be to any depth). If isShallow
is truey, the array will only be flattened a single level. If a callback is provided each element of the array is passed through the callback before flattening. The callback is bound to thisArg
and invoked with three arguments; (value, index, array).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to flatten.[isShallow=false]
(boolean): A flag to restrict flattening to a single level.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a new flattened array.
_.flatten([1, [2], [3, [[4]]]]);
// => [1, 2, 3, 4];
// using `isShallow`
_.flatten([1, [2], [3, [[4]]]], true);
// => [1, 2, 3, [[4]]];
var characters = [
{ 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
];
// using "_.pluck" callback shorthand
_.flatten(characters, 'pets');
// => ['hoppy', 'baby puss', 'dino']
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 providing true
for fromIndex
will run a faster binary search.
array
(Array): The array to search.value
(*): The value to search for.[fromIndex=0]
(boolean|number): The index to search from ortrue
to perform a binary search on a sorted array.
(number): Returns the index of the matched value or -1
.
_.indexOf([1, 2, 3, 1, 2, 3], 2);
// => 1
// using `fromIndex`
_.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
// => 4
// performing a binary search
_.indexOf([1, 1, 2, 2, 3, 3], 2, true);
// => 2
Gets all but the last element or last n
elements of an array. If a callback is provided elements at the end of the array are excluded from the result as long as the callback returns truey. The callback is bound to thisArg
and invoked with three arguments; (value, index, array).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to query.[callback=1]
(Function|Object|number|string): The function called per element or the number of elements to exclude. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a slice of array
.
_.initial([1, 2, 3]);
// => [1, 2]
// excludes the last two elements
_.initial([1, 2, 3], 2);
// => [1]
// excludes elements from the end until the callback fails
_.initial([1, 2, 3], function(num) {
return num > 1;
});
// => [1]
var characters = [
{ 'name': 'barney', 'employer': 'slate' },
{ 'name': 'fred', 'employer': 'slate', 'blocked': true },
{ 'name': 'pebbles', 'employer': 'na', 'blocked': true }
];
// using "_.pluck" callback shorthand
_.initial(characters, 'blocked');
// => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }]
// using "_.where" callback shorthand
_.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
// => ['barney', 'fred']
Creates an array of unique values present in all provided arrays using strict equality for comparisons, i.e. ===
.
[array]
(...Array): The arrays to inspect.
(Array): Returns an array of shared values.
_.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
// => [1, 2]
Gets the last element or last n
elements of an array. If a callback is provided elements at the end of the array are returned as long as the callback returns truey. The callback is bound to thisArg
and invoked with three arguments; (value, index, array).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to query.[callback]
(Function|Object|number|string): The function called per element or the number of elements to return. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the last element(s) of array
.
_.last([1, 2, 3]);
// => 3
// returns the last two elements
_.last([1, 2, 3], 2);
// => [2, 3]
// returns elements from the end until the callback fails
_.last([1, 2, 3], function(num) {
return num > 1;
});
// => [2, 3]
var characters = [
{ 'name': 'barney', 'employer': 'slate' },
{ 'name': 'fred', 'employer': 'slate', 'blocked': true },
{ 'name': 'pebbles', 'employer': 'na', 'blocked': true }
];
// using "_.pluck" callback shorthand
_.pluck(_.last(characters, 'blocked'), 'name');
// => ['fred', 'pebbles']
// using "_.where" callback shorthand
_.last(characters, { 'employer': 'na' });
// => [{ 'name': 'pebbles', 'employer': 'na', 'blocked': true }]
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.
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to search.value
(*): 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
// using `fromIndex`
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
// => 1
Removes all provided values from array
using strict equality for comparisons, i.e. ===
.
array
(Array): The array to modify.[value]
(...*): The values to remove.
(Array): Returns array
.
var array = [1, 2, 3, 1, 2, 3];
_.pull(array, 2, 3);
console.log(array);
// => [1, 1]
Creates an array of numbers (positive and/or negative) progressing from start
up to but not including end
. If start
is less than stop
a zero-length range is created unless a negative step
is specified.
[start=0]
(number): The start of the range.end
(number): The end of the range.[step=1]
(number): The value to increment or decrement by.
(Array): Returns a new range array.
_.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);
// => []
Removes all elements from an array that the callback returns truey for and returns an array of removed elements. The callback is bound to thisArg
and invoked with three arguments; (value, index, array).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to modify.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a new array of removed elements.
var array = [1, 2, 3, 4, 5, 6];
var evens = _.remove(array, function(num) { return num % 2 == 0; });
console.log(array);
// => [1, 3, 5]
console.log(evens);
// => [2, 4, 6]
The opposite of _.initial
; this method gets all but the first element or first n
elements of an array. If a callback function is provided elements at the beginning of the array are excluded from the result as long as the callback returns truey. The callback is bound to thisArg
and invoked with three arguments; (value, index, array).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.drop, _.tail
array
(Array): The array to query.[callback=1]
(Function|Object|number|string): The function called per element or the number of elements to exclude. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a slice of array
.
_.rest([1, 2, 3]);
// => [2, 3]
// excludes the first two elements
_.rest([1, 2, 3], 2);
// => [3]
// excludes elements from the beginning until the callback fails
_.rest([1, 2, 3], function(num) {
return num < 3;
});
// => [3]
var characters = [
{ 'name': 'barney', 'employer': 'slate', 'blocked': true },
{ 'name': 'fred', 'employer': 'slate' },
{ 'name': 'pebbles', 'employer': 'na', 'blocked': true }
];
// using "_.pluck" callback shorthand
_.pluck(_.rest(characters, 'blocked'), 'name');
// => ['fred', 'pebbles']
// using "_.where" callback shorthand
_.rest(characters, { 'employer': 'slate' });
// => [{ 'name': 'pebbles', 'employer': 'na', 'blocked': true }]
Slices array
from the start
index up to, but not including, the end
index.
Note: This function is used instead of Array#slice
to support node lists in IE < 9
and to ensure dense arrays are returned.
array
(Array): The array to slice.[start=0]
(number): The start index.[end=array.length]
(number): The end index.
(Array): Returns the new array.
Uses a binary search to determine the smallest index at which a value should be inserted into a given sorted array in order to maintain the sort order of the array. If a callback is provided it will be executed for value
and each element of array
to compute their sort ranking. The callback is bound to thisArg
and invoked with one argument; (value).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
array
(Array): The array to inspect.value
(*): The value to evaluate.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(number): Returns the index at which value
should be inserted into array
.
_.sortedIndex([20, 30, 50], 40);
// => 2
var dict = {
'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
};
// using `callback`
_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return dict.wordToNumber[word];
});
// => 2
// using `callback` with `thisArg`
_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return this.wordToNumber[word];
}, dict);
// => 2
// using "_.pluck" callback shorthand
_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
// => 2
Creates an array of unique values, in order, of the provided arrays using strict equality for comparisons, i.e. ===
.
[array]
(...Array): The arrays to inspect.
(Array): Returns an array of combined values.
_.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
// => [1, 2, 3, 5, 4]
Creates a duplicate-value-free version of an array using strict equality for comparisons, i.e. ===
. If the array is sorted, providing true
for isSorted
will use a faster algorithm. If a callback is provided each element of array
is passed through the callback before uniqueness is computed. The callback is bound to thisArg
and invoked with three arguments; (value, index, array).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.unique
array
(Array): The array to process.[isSorted=false]
(boolean): A flag to indicate thatarray
is sorted.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a duplicate-value-free array.
_.uniq([1, 2, 1, 3, 1]);
// => [1, 2, 3]
// using `isSorted`
_.uniq([1, 1, 2, 2, 3], true);
// => [1, 2, 3]
// using `callback`
_.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
// => ['A', 'b', 'C']
// using `callback` with `thisArg`
_.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
// => [1, 2.5, 3]
// using "_.pluck" callback shorthand
_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]
Creates an array excluding all provided values using strict equality for comparisons, i.e. ===
.
array
(Array): The array to filter.[value]
(...*): The values to exclude.
(Array): Returns a new array of filtered values.
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
// => [2, 3, 4]
Creates an array that is the symmetric difference of the provided arrays. See [Wikipedia](http://en.wikipedia.org/wiki/Symmetric_difference) for more details.
[array]
(...Array): The arrays to inspect.
(Array): Returns an array of values.
_.xor([1, 2, 3], [5, 2, 1, 4]);
// => [3, 5, 4]
_.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
// => [1, 4, 5]
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. If a zipped value is provided its corresponding unzipped value will be returned.
_.unzip
[array]
(...Array): The arrays to process.
(Array): Returns a new array of grouped elements.
_.zip(['fred', 'barney'], [30, 40], [true, false]);
// => [['fred', 30, true], ['barney', 40, false]]
_.unzip([['fred', 30, true], ['barney', 40, false]]);
// => [['fred', 'barney'], [30, 40], [true, false]]
Creates an object composed from arrays of keys
and values
. Provide either a single two dimensional array, i.e. [[key1, value1], [key2, value2]]
or two arrays, one of keys
and one of corresponding values
.
_.object
keys
(Array): The array of keys.[values=[]]
(Array): The array of values.
(Object): Returns an object composed of the given keys and corresponding values.
_.zipObject(['fred', 'barney'], [30, 40]);
// => { 'fred': 30, 'barney': 40 }
Creates a lodash
object which wraps the given value to enable intuitive method chaining.
In addition to Lo-Dash methods, wrappers also have the following Array
methods:
concat
, join
, pop
, push
, reverse
, shift
, slice
, sort
, splice
, and unshift
Chaining is supported in custom builds as long as the value
method is implicitly or explicitly included in the build.
The chainable wrapper functions are:
after
, assign
, bind
, bindAll
, bindKey
, chain
, compact
, compose
, concat
, constant
, countBy
, create
, createCallback
, curry
, debounce
, defaults
, defer
, delay
, difference
, filter
, flatten
, forEach
, forEachRight
, forIn
, forInRight
, forOwn
, forOwnRight
, functions
, groupBy
, indexBy
, initial
, intersection
, invert
, invoke
, keys
, map
, mapValues
, matches
, max
, memoize
, merge
, min
, noop
, object
, omit
, once
, pairs
, partial
, partialRight
, pick
, pluck
, property
, pull
, push
, range
, reject
, remove
, rest
, reverse
, shuffle
, slice
, sort
, sortBy
, splice
, tap
, throttle
, times
, toArray
, transform
, union
, uniq
, unshift
, unzip
, values
, where
, without
, wrap
, xor
, and zip
The non-chainable wrapper functions are:
capitalize
, clone
, cloneDeep
, contains
, escape
, every
, find
, findIndex
, findKey
, findLast
, findLastIndex
, findLastKey
, has
, identity
, indexOf
, isArguments
, isArray
, isBoolean
, isDate
, isElement
, isEmpty
, isEqual
, isFinite
, isFunction
, isNaN
, isNull
, isNumber
, isObject
, isPlainObject
, isRegExp
, isString
, isUndefined
, join
, lastIndexOf
, mixin
, noConflict
, now
, parseInt
, pop
, random
, reduce
, reduceRight
, result
, shift
, size
, some
, sortedIndex
, runInContext
, template
, trim
, trimLeft
, trimRight
, unescape
, uniqueId
, and value
The wrapper functions first
, last
, and sample
return wrapped values when n
is provided, otherwise they return unwrapped values.
Explicit chaining can be enabled by using the _.chain
method.
value
(*): The value to wrap in alodash
instance.
(Object): Returns a lodash
instance.
var wrapped = _([1, 2, 3]);
// returns an unwrapped value
wrapped.reduce(function(sum, num) {
return sum + num;
});
// => 6
// returns a wrapped value
var squares = wrapped.map(function(num) {
return num * num;
});
_.isArray(squares);
// => false
_.isArray(squares.value());
// => true
Creates a lodash
object that wraps value
with explicit method chaining enabled.
value
(*): The value to wrap.
(Object): Returns the wrapper object.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 },
{ 'name': 'pebbles', 'age': 1 }
];
var youngest = _.chain(characters)
.sortBy('age')
.map(function(chr) { return chr.name + ' is ' + chr.age; })
.first()
.value();
// => 'pebbles is 1'
This method invokes interceptor
and returns value
. The interceptor is bound to thisArg
and 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.
value
(*): The value to provide tointerceptor
.interceptor
(Function): The function to invoke.[thisArg]
(*): Thethis
binding ofinterceptor
.
(*): Returns value
.
_([1, 2, 3, 4])
.tap(function(array) { array.pop(); })
.reverse()
.value();
// => [3, 2, 1]
Enables explicit method chaining on the wrapper object.
(*): Returns the wrapper object.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
// without explicit chaining
_(characters).first();
// => { 'name': 'barney', 'age': 36 }
// with explicit chaining
_(characters).chain()
.first()
.pick('age')
.value();
// => { 'age': 36 }
Produces the toString
result of the wrapped value.
(string): Returns the string result.
_([1, 2, 3]).toString();
// => '1,2,3'
Extracts the wrapped value.
_.prototype.value
(*): Returns the wrapped value.
_([1, 2, 3]).valueOf();
// => [1, 2, 3]
Creates an array of elements from the specified indexes, or keys, of the collection
. Indexes may be specified as individual arguments or as arrays of indexes.
collection
(Array|Object|string): The collection to iterate over.[index]
(...(number|number[]|string|string[]): The indexes ofcollection
to retrieve, specified as individual indexes or arrays of indexes.
(Array): Returns a new array of elements corresponding to the provided indexes.
_.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
// => ['a', 'c', 'e']
_.at(['fred', 'barney', 'pebbles'], 0, 2);
// => ['fred', 'pebbles']
Checks if a given value 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
(*): 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': 'fred', 'age': 40 }, 'fred');
// => true
_.contains('pebbles', 'eb');
// => true
Creates an object composed of keys generated from the results of running each element of collection
through the callback. The corresponding value of each key is the number of times the key was returned by the callback. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): 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 truey value for **all** elements of a collection. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.all
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(boolean): Returns true
if all elements passed the callback check, else false
.
_.every([true, 1, null, 'yes']);
// => false
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
// using "_.pluck" callback shorthand
_.every(characters, 'age');
// => true
// using "_.where" callback shorthand
_.every(characters, { 'age': 36 });
// => false
Iterates over elements of a collection, returning an array of all elements the callback returns truey for. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.select
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a new array of elements that passed the callback check.
var evens = _.filter([1, 2, 3, 4], function(num) { return num % 2 == 0; });
// => [2, 4]
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40, 'blocked': true }
];
// using "_.pluck" callback shorthand
_.filter(characters, 'blocked');
// => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
// using "_.where" callback shorthand
_.filter(characters, { 'age': 36 });
// => [{ 'name': 'barney', 'age': 36 }]
Iterates over elements of a collection, returning the first element that the callback returns truey for. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.detect, _.findWhere
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the found element, else undefined
.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40, 'blocked': true },
{ 'name': 'pebbles', 'age': 1 }
];
_.find(characters, function(chr) {
return chr.age < 40;
});
// => { 'name': 'barney', 'age': 36 }
// using "_.where" callback shorthand
_.find(characters, { 'age': 1 });
// => { 'name': 'pebbles', 'age': 1 }
// using "_.pluck" callback shorthand
_.find(characters, 'blocked');
// => { 'name': 'fred', 'age': 40, 'blocked': true }
This method is like _.find
except that it iterates over elements of a collection
from right to left.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the found element, else undefined
.
_.findLast([1, 2, 3, 4], function(num) {
return num % 2 == 1;
});
// => 3
Iterates over elements of a collection, executing the callback for each element. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection). Callbacks 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 _.forIn
or _.forOwn
may be used for object iteration.
_.each
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): Thethis
binding ofcallback
.
(Array, Object, string): Returns collection
.
_([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
// => logs each number and returns '1,2,3'
_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
// => logs each number and returns the object (property order is not guaranteed across environments)
This method is like _.forEach
except that it iterates over elements of a collection
from right to left.
_.eachRight
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): Thethis
binding ofcallback
.
(Array, Object, string): Returns collection
.
_([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
// => logs each number from right to left and returns '3,2,1'
Creates an object composed of keys generated from the results of running each element of a collection through the callback. The corresponding value of each key is an array of the elements responsible for generating the key. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): 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] }
// using "_.pluck" callback shorthand
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }
Creates an object composed of keys generated from the results of running each element of the collection through the given callback. The corresponding value of each key is the last element responsible for generating the key. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns the composed aggregate object.
var keys = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
_.indexBy(keys, 'dir');
// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
_.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
_.indexBy(keys, function(key) { return this.fromCharCode(key.code); }, String);
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
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 provided 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.[args]
(...*): 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 the callback. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.collect
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): 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] (property order is not guaranteed across environments)
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
// using "_.pluck" callback shorthand
_.map(characters, 'name');
// => ['barney', 'fred']
Retrieves the maximum value of a collection. If the collection is empty or falsey -Infinity
is returned. If a callback is provided it will be executed for each value in the collection to generate the criterion by which the value is ranked. The callback is bound to thisArg
and invoked with three arguments; (value, index, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the maximum value.
_.max([4, 2, 8, 6]);
// => 8
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
_.max(characters, function(chr) { return chr.age; });
// => { 'name': 'fred', 'age': 40 };
// using "_.pluck" callback shorthand
_.max(characters, 'age');
// => { 'name': 'fred', 'age': 40 };
Retrieves the minimum value of a collection. If the collection is empty or falsey Infinity
is returned. If a callback is provided it will be executed for each value in the collection to generate the criterion by which the value is ranked. The callback is bound to thisArg
and invoked with three arguments; (value, index, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the minimum value.
_.min([4, 2, 8, 6]);
// => 2
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
_.min(characters, function(chr) { return chr.age; });
// => { 'name': 'barney', 'age': 36 };
// using "_.pluck" callback shorthand
_.min(characters, 'age');
// => { 'name': 'barney', 'age': 36 };
Creates an array of elements split into two groups, the first of which contains elements the callback returns truey for, while the second of which contains elements the callback returns falsey for. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a new array of grouped elements.
_.partition([1, 2, 3], function(num) { return num % 2; });
// => [[1, 3], [2]]
_.partition([1.2, 2.3, 3.4], function(num) { return this.floor(num) % 2; }, Math);
// => [[1, 3], [2]]
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40, 'blocked': true },
{ 'name': 'pebbles', 'age': 1 }
];
// using "_.where" callback shorthand
_.map(_.partition(characters, { 'age': 1 }), function(array) { return _.pluck(array, 'name'); });
// => [['pebbles'], ['barney', 'fred']]
// using "_.pluck" callback shorthand
_.map(_.partition(characters, 'blocked'), function(array) { return _.pluck(array, 'name'); });
// => [['fred'], ['barney', 'pebbles']]
Retrieves the value of a specified property from all elements in the collection.
collection
(Array|Object|string): The collection to iterate over.key
(string): The name of the property to pluck.
(Array): Returns a new array of property values.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
_.pluck(characters, 'name');
// => ['barney', 'fred']
Reduces a collection to a value which is the accumulated result of running each element in the collection through the callback, where each successive callback execution consumes the return value of the previous execution. If accumulator
is not provided the first element of the collection will be used as the initial accumulator
value. The callback is bound to thisArg
and invoked with four arguments; (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]
(*): Initial value of the accumulator.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the accumulated value.
var sum = _.reduce([1, 2, 3], function(sum, num) {
return sum + num;
});
// => 6
var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
result[key] = num * 3;
return result;
}, {});
// => { 'a': 3, 'b': 6, 'c': 9 }
This method is like _.reduce
except that it iterates over elements of a collection
from right to left.
_.foldr
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[accumulator]
(*): Initial value of the accumulator.[thisArg]
(*): Thethis
binding ofcallback
.
(*): 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 elements of a collection that the callback does **not** return truey for.
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Array): Returns a new array of elements that failed the callback check.
var odds = _.reject([1, 2, 3, 4], function(num) { return num % 2 == 0; });
// => [1, 3]
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40, 'blocked': true }
];
// using "_.pluck" callback shorthand
_.reject(characters, 'blocked');
// => [{ 'name': 'barney', 'age': 36 }]
// using "_.where" callback shorthand
_.reject(characters, { 'age': 36 });
// => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
Retrieves a random element or n
random elements from a collection.
collection
(Array|Object|string): The collection to sample.[n]
(number): The number of elements to sample.
(*): Returns the random sample(s) of collection
.
_.sample([1, 2, 3, 4]);
// => 2
_.sample([1, 2, 3, 4], 2);
// => [3, 1]
Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. See [Wikipedia](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle) for more details.
collection
(Array|Object|string): The collection to shuffle.
(Array): Returns a new shuffled collection.
_.shuffle([1, 2, 3, 4]);
// => [4, 1, 3, 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('pebbles');
// => 7
Checks if the callback returns a truey value for **any** element of a collection. The function returns as soon as it finds a 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).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
_.any
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(boolean): Returns true
if any element passed the callback check, else false
.
_.some([null, 0, 'yes', false], Boolean);
// => true
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40, 'blocked': true }
];
// using "_.pluck" callback shorthand
_.some(characters, 'blocked');
// => true
// using "_.where" callback shorthand
_.some(characters, { 'age': 1 });
// => false
Creates an array of elements, sorted in ascending order by the results of running each element in a collection through the callback. This method performs a stable sort, that is, it will preserve the original sort order of equal elements. The callback is bound to thisArg
and invoked with three arguments; (value, index|key, collection).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an array of property names is provided for callback
the collection will be sorted by each property value.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Array|Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): 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]
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 },
{ 'name': 'barney', 'age': 26 },
{ 'name': 'fred', 'age': 30 }
];
// using "_.pluck" callback shorthand
_.map(_.sortBy(characters, 'age'), _.values);
// => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
// sorting by multiple properties
_.map(_.sortBy(characters, ['name', 'age']), _.values);
// = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
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]
Performs a deep comparison between each element in collection
and the source
object, returning an array of all elements that have equivalent property values.
collection
(Array|Object|string): The collection to iterate over.source
(Object): The object of property values to filter by.
(Array): Returns a new array of elements that have the given properties.
var characters = [
{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
];
_.where(characters, { 'age': 36 });
// => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
_.where(characters, { 'pets': ['dino'] });
// => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
Creates a function that executes func
, with the this
binding and arguments of the created function, only after being called n
times.
n
(number): The number of times the function must be called beforefunc
is executed.func
(Function): The function to restrict.
(Function): Returns the new restricted function.
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 all saves have completed
Creates a function that, when called, invokes func
with the this
binding of thisArg
and prepends any additional bind
arguments to those provided to the bound function.
Note: Unlike native Function#bind
this method does not set the length
property of bound functions.
func
(Function): The function to bind.[thisArg]
(*): Thethis
binding offunc
.[args]
(...*): Arguments to be partially applied.
(Function): Returns the new bound function.
var func = function(greeting) {
return greeting + ' ' + this.name;
};
func = _.bind(func, { 'name': 'fred' }, 'hi');
func();
// => 'hi fred'
Binds methods of an object to the object itself, overwriting the existing method. Method names may be specified as individual arguments or as arrays of method names. If no method names are provided all the function properties of object
will be bound.
Note: This method does not set the length
property of bound functions.
object
(Object): The object to bind and assign the bound methods to.[methodName]
(...string): The object method names to bind, specified as individual method names or arrays of method names.
(Object): Returns object
.
var view = {
'label': 'docs',
'onClick': function() { console.log('clicked ' + this.label); }
};
_.bindAll(view);
jQuery('#docs').on('click', view.onClick);
// => logs 'clicked docs', when the button is clicked
Creates a function that, when called, 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 will be redefined or don't yet exist. See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern) for more details.
object
(Object): The object the method belongs to.key
(string): The key of the method.[args]
(...*): Arguments to be partially applied.
(Function): Returns the new bound function.
var object = {
'name': 'fred',
'greet': function(greeting) {
return greeting + ' ' + this.name;
}
};
var func = _.bindKey(object, 'greet', 'hi');
func();
// => 'hi fred'
object.greet = function(greeting) {
return greeting + 'ya ' + this.name + '!';
};
func();
// => 'hiya fred!'
Creates a function that is the composition of the provided functions, where each function consumes the return value of the function that follows. For example, composing the functions f()
, g()
, and h()
produces f(g(h()))
. Each function is executed with the this
binding of the composed function.
[func]
(...Function): Functions to compose.
(Function): Returns the new composed function.
var realNameMap = {
'pebbles': 'penelope'
};
var format = function(name) {
name = realNameMap[name.toLowerCase()] || name;
return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
};
var greet = function(formatted) {
return 'Hiya ' + formatted + '!';
};
var welcome = _.compose(greet, format);
welcome('pebbles');
// => 'Hiya Penelope!'
Creates a function which accepts one or more arguments of func
that when invoked either executes 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
can be specified if func.length
is not sufficient.
Note: This method does not set the length
property of curried functions.
func
(Function): The function to curry.[arity=func.length]
(number): The arity offunc
.
(Function): Returns the new curried function.
var curried = _.curry(function(a, b, c) {
console.log(a + b + c);
});
curried(1)(2)(3);
// => 6
curried(1, 2)(3);
// => 6
curried(1, 2, 3);
// => 6
Creates a function that will delay the execution of func
until after wait
milliseconds have elapsed since the last time it was invoked. 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 will return the result of the last func
call.
Note: If leading
and trailing
options are true
func
will be called on the trailing edge of the timeout only if the the debounced function is invoked more than once during the wait
timeout.
func
(Function): The function to debounce.wait
(number): The number of milliseconds to delay.[options]
(Object): The options object.[options.leading=false]
(boolean): Specify execution on the leading edge of the timeout.[options.maxWait]
(number): The maximum timefunc
is allowed to be delayed before it's called.[options.trailing=true]
(boolean): Specify execution on the trailing edge of the timeout.
(Function): Returns the new debounced function.
// avoid costly calculations while the window size is in flux
var lazyLayout = _.debounce(calculateLayout, 150);
jQuery(window).on('resize', lazyLayout);
// execute `sendMail` when the click event is fired, debouncing subsequent calls
jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
'leading': true,
'trailing': false
});
// ensure `batchLog` is executed once after 1 second of debounced calls
var source = new EventSource('/stream');
source.addEventListener('message', _.debounce(batchLog, 250, {
'maxWait': 1000
}, false);
Defers executing the func
function until the current call stack has cleared. Additional arguments will be provided to func
when it is invoked.
func
(Function): The function to defer.[args]
(...*): Arguments to invoke the function with.
(number): Returns the timer id.
_.defer(function(text) { console.log(text); }, 'deferred');
// logs 'deferred' after one or more milliseconds
Executes the func
function after wait
milliseconds. Additional arguments will be provided to func
when it is invoked.
func
(Function): The function to delay.wait
(number): The number of milliseconds to delay execution.[args]
(...*): Arguments to invoke the function with.
(number): Returns the timer id.
_.delay(function(text) { console.log(text); }, 1000, 'later');
// => logs 'later' after one second
Creates a function that memoizes the result of func
. If resolver
is provided it will be used to determine 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 cache key. The func
is executed with the this
binding of the memoized function. The result cache is exposed as the cache
property on 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);
});
fibonacci(9)
// => 34
var data = {
'fred': { 'name': 'fred', 'age': 40 },
'pebbles': { 'name': 'pebbles', 'age': 1 }
};
// modifying the result cache
var get = _.memoize(function(name) { return data[name]; }, _.identity);
get('pebbles');
// => { 'name': 'pebbles', 'age': 1 }
get.cache.pebbles.name = 'penelope';
get('pebbles');
// => { 'name': 'penelope', 'age': 1 }
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();
// `initialize` executes `createApplication` once
Creates a function that, when called, invokes func
with any additional partial
arguments prepended to those provided to the new function. This method is similar to _.bind
except it does **not** alter the this
binding.
Note: This method does not set the length
property of partially applied functions.
func
(Function): The function to partially apply arguments to.[args]
(...*): 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('fred');
// => 'hi fred'
This method is like _.partial
except that partially applied arguments are appended to those provided to the new function.
Note: This method does not set the length
property of partially applied functions.
func
(Function): The function to partially apply arguments to.[args]
(...*): Arguments to be partially applied.
(Function): Returns the new partially applied function.
var defaultsDeep = _.partialRight(_.merge, _.defaults);
var options = {
'variable': 'data',
'imports': { 'jq': $ }
};
defaultsDeep(options, _.templateSettings);
options.variable
// => 'data'
options.imports
// => { '_': _, 'jq': $ }
Creates a function that, when executed, will only call the func
function at most once per every wait
milliseconds. 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 will return the result of the last func
call.
Note: If leading
and trailing
options are true
func
will be called on the trailing edge of the timeout only if the the throttled function is invoked more than once during the wait
timeout.
func
(Function): The function to throttle.wait
(number): The number of milliseconds to throttle executions to.[options]
(Object): The options object.[options.leading=true]
(boolean): Specify execution on the leading edge of the timeout.[options.trailing=true]
(boolean): Specify execution on the trailing edge of the timeout.
(Function): Returns the new throttled function.
// avoid excessively updating the position while scrolling
var throttled = _.throttle(updatePosition, 100);
jQuery(window).on('scroll', throttled);
// execute `renewToken` when the click event is fired, but not more than once every 5 minutes
jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
'trailing': false
}));
Creates a function that provides value
to the wrapper function as its first argument. Additional arguments provided to the function are appended to those provided to the wrapper function. The wrapper is executed with the this
binding of the created function.
value
(*): The value to wrap.wrapper
(Function): The wrapper function.
(Function): Returns the new function.
var p = _.wrap(_.escape, function(func, text) {
return '<p>' + func(text) + '</p>';
});
p('fred, barney, & pebbles');
// => '<p>fred, barney, & pebbles</p>'
Assigns own enumerable properties of source object(s) to the destination object. Subsequent sources will overwrite property assignments of previous sources. If a callback is provided it will be executed to produce the assigned values. The callback is bound to thisArg
and invoked with two arguments; (objectValue, sourceValue).
_.extend
object
(Object): The destination object.[source]
(...Object): The source objects.[callback]
(Function): The function to customize assigning values.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns the destination object.
_.assign({ 'name': 'fred' }, { 'employer': 'slate' });
// => { 'name': 'fred', 'employer': 'slate' }
var defaults = _.partialRight(_.assign, function(a, b) {
return typeof a == 'undefined' ? b : a;
});
defaults({ 'name': 'barney' }, { 'name': 'fred', 'employer': 'slate' });
// => { 'name': 'barney', 'employer': 'slate' }
Creates a clone of value
. If isDeep
is true
nested objects will also be cloned, otherwise they will be assigned by reference. If a callback is provided it will be executed to produce the cloned values. If the callback returns undefined
cloning will be handled by the method instead. The callback is bound to thisArg
and invoked with one argument; (value).
Note: This method is loosely based on the structured clone algorithm. 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. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm) for more details.
value
(*): The value to clone.[isDeep=false]
(boolean): Specify a deep clone.[callback]
(Function): The function to customize cloning values.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the cloned value.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
var shallow = _.clone(characters);
shallow[0] === characters[0];
// => true
var deep = _.clone(characters, true);
deep[0] === characters[0];
// => false
_.mixin({
'clone': _.partialRight(_.clone, function(value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
})
});
var clone = _.clone(document.body);
clone.childNodes.length;
// => 0
Creates a deep clone of value
. If a callback is provided it will be executed to produce the cloned values. If the callback returns undefined
cloning will be handled by the method instead. The callback is bound to thisArg
and invoked with one argument; (value).
Note: This method is loosely based on the structured clone algorithm. 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. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm) for more details.
value
(*): The value to deep clone.[callback]
(Function): The function to customize cloning values.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the deep cloned value.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
var deep = _.cloneDeep(characters);
deep[0] === characters[0];
// => false
var view = {
'label': 'docs',
'node': element
};
var clone = _.cloneDeep(view, function(value) {
return _.isElement(value) ? value.cloneNode(true) : undefined;
});
clone.node == view.node;
// => false
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.
prototype
(Object): The object to inherit from.[properties]
(Object): The properties to assign to the object.
(Object): Returns the new object.
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
Assigns own enumerable properties of source object(s) to the destination object for all destination properties that resolve to undefined
. Once a property is set, additional defaults of the same property will be ignored.
object
(Object): The destination object.[source]
(...Object): The source objects.
(Object): Returns the destination object.
_.defaults({ 'name': 'barney' }, { 'name': 'fred', 'employer': 'slate' });
// => { 'name': 'barney', 'employer': 'slate' }
This method is like _.findIndex
except that it returns the key of the first element that passes the callback check, instead of the element itself.
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
object
(Object): The object to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(string, undefined): Returns the key of the found element, else undefined
.
var characters = {
'barney': { 'age': 36 },
'fred': { 'age': 40, 'blocked': true },
'pebbles': { 'age': 1 }
};
_.findKey(characters, function(chr) {
return chr.age < 40;
});
// => 'barney' (property order is not guaranteed across environments)
// using "_.where" callback shorthand
_.findKey(characters, { 'age': 1 });
// => 'pebbles'
// using "_.pluck" callback shorthand
_.findKey(characters, 'blocked');
// => 'fred'
This method is like _.findKey
except that it iterates over elements of a collection
in the opposite order.
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
object
(Object): The object to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(string, undefined): Returns the key of the found element, else undefined
.
var characters = {
'barney': { 'age': 36, 'blocked': true },
'fred': { 'age': 40 },
'pebbles': { 'age': 1, 'blocked': true }
};
_.findLastKey(characters, function(chr) {
return chr.age < 40;
});
// => returns `pebbles`, assuming `_.findKey` returns `barney`
// using "_.where" callback shorthand
_.findLastKey(characters, { 'age': 40 });
// => 'fred'
// using "_.pluck" callback shorthand
_.findLastKey(characters, 'blocked');
// => 'pebbles'
Iterates over own and inherited enumerable properties of an object, 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]
(*): Thethis
binding ofcallback
.
(Object): Returns object
.
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
};
_.forIn(new Shape, function(value, key) {
console.log(key);
});
// => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
This method is like _.forIn
except that it iterates over elements of a collection
in the opposite order.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns object
.
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
};
_.forInRight(new Shape, function(value, key) {
console.log(key);
});
// => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
Iterates over own enumerable properties of an object, 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]
(*): Thethis
binding ofcallback
.
(Object): Returns object
.
_.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
console.log(key);
});
// => logs '0', '1', and 'length' (property order is not guaranteed across environments)
This method is like _.forOwn
except that it iterates over elements of a collection
in the opposite order.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns object
.
_.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
console.log(key);
});
// => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
Creates a sorted array of property names of all enumerable properties, own and inherited, of object
that have function values.
_.methods
object
(Object): The object to inspect.
(Array): Returns an array of property names that have function values.
_.functions(_);
// => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
Checks if the specified property name exists as a direct property of object
, instead of an inherited property.
object
(Object): The object to inspect.key
(string): The name of the property to check.
(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. If the given object contains duplicate values, subsequent values will overwrite property assignments of previous values unless multiValue
is true
.
object
(Object): The object to invert.[multiValue=false]
(boolean): Allow multiple values per key.
(Object): Returns the created inverted object.
_.invert({ 'first': 'fred', 'second': 'barney' });
// => { 'fred': 'first', 'barney': 'second' }
// without `multiValue`
_.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' });
// => { 'fred': 'third', 'barney': 'second' }
// with `multiValue`
_.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' }, true);
// => { 'fred': ['first', 'third'], 'barney': ['second'] }
Checks if value
is an arguments
object.
value
(*): 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
(*): 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 value.
value
(*): 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
(*): 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
(*): 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. If a callback is provided it will be executed to compare values. If the callback returns undefined
comparisons will be handled by the method instead. The callback is bound to thisArg
and invoked with two arguments; (a, b).
a
(*): The value to compare.b
(*): The other value to compare.[callback]
(Function): The function to customize comparing values.[thisArg]
(*): Thethis
binding ofcallback
.
(boolean): Returns true
if the values are equivalent, else false
.
var object = { 'name': 'fred' };
var copy = { 'name': 'fred' };
object == copy;
// => false
_.isEqual(object, copy);
// => true
var words = ['hello', 'goodbye'];
var otherWords = ['hi', 'goodbye'];
_.isEqual(words, otherWords, function(a, b) {
var reGreet = /^(?:hello|hi)$/i,
aGreet = _.isString(a) && reGreet.test(a),
bGreet = _.isString(b) && reGreet.test(b);
return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
});
// => true
Checks if value
is, or can be coerced to, a finite number.
Note: This method is not the same as native isFinite
which will return true
for booleans and empty strings. See the [ES5 spec](http://es5.github.io/#x15.1.2.5) for more details.
value
(*): The value to check.
(boolean): Returns true
if the value
is finite, else false
.
_.isFinite(-101);
// => true
_.isFinite('10');
// => true
_.isFinite(true);
// => false
_.isFinite('');
// => false
_.isFinite(Infinity);
// => false
Checks if value
is a function.
value
(*): The value to check.
(boolean): Returns true
if the value
is a function, else false
.
_.isFunction(_);
// => true
Checks if value
is NaN
.
Note: This method is not the same as native isNaN
which will return true
for undefined
and other non-numeric values. See the [ES5 spec](http://es5.github.io/#x15.1.2.4) for more details.
value
(*): 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
(*): 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.
Note: NaN
is considered a number. See the [ES5 spec](http://es5.github.io/#x8.5) for more details.
value
(*): 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
(*): 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 value
is an object created by the Object
constructor.
value
(*): The value to check.
(boolean): Returns true
if value
is a plain object, else false
.
function Shape() {
this.x = 0;
this.y = 0;
}
_.isPlainObject(new Shape);
// => false
_.isPlainObject([1, 2, 3]);
// => false
_.isPlainObject({ 'x': 0, 'y': 0 });
// => true
Checks if value
is a regular expression.
value
(*): The value to check.
(boolean): Returns true
if the value
is a regular expression, else false
.
_.isRegExp(/fred/);
// => true
Checks if value
is a string.
value
(*): The value to check.
(boolean): Returns true
if the value
is a string, else false
.
_.isString('fred');
// => true
Checks if value
is undefined
.
value
(*): 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 an object.
object
(Object): The object to inspect.
(Array): Returns an array of property names.
_.keys({ 'one': 1, 'two': 2, 'three': 3 });
// => ['one', 'two', 'three'] (property order is not guaranteed across environments)
Creates an object with the same keys as object
and values generated by running each own enumerable property of object
through the callback. The callback is bound to thisArg
and invoked with three arguments; (value, key, object).
If a property name is provided for callback
the created "_.pluck" style callback will return the property value of the given element.
If an object is provided for callback
the created "_.where" style callback will return true
for elements that have the properties of the given object, else false
.
object
(Object): The object to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns a new object with values of the results of each callback
execution.
_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
// => { 'a': 3, 'b': 6, 'c': 9 }
var characters = {
'fred': { 'name': 'fred', 'age': 40 },
'pebbles': { 'name': 'pebbles', 'age': 1 }
};
// using "_.pluck" callback shorthand
_.mapValues(characters, 'age');
// => { 'fred': 40, 'pebbles': 1 }
Recursively merges own enumerable properties of the source object(s), that don't resolve to undefined
into the destination object. Subsequent sources will overwrite property assignments of previous sources. If a callback is provided it will be executed to produce the merged values of the destination and source properties. If the callback returns undefined
merging will be handled by the method instead. The callback is bound to thisArg
and invoked with two arguments; (objectValue, sourceValue).
object
(Object): The destination object.[source]
(...Object): The source objects.[callback]
(Function): The function to customize merging properties.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns the destination object.
var names = {
'characters': [
{ 'name': 'barney' },
{ 'name': 'fred' }
]
};
var ages = {
'characters': [
{ 'age': 36 },
{ 'age': 40 }
]
};
_.merge(names, ages);
// => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
var food = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var otherFood = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.merge(food, otherFood, function(a, b) {
return _.isArray(a) ? a.concat(b) : undefined;
});
// => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
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 a callback is provided it will be executed for each property of object
omitting the properties the callback returns truey for. The callback is bound to thisArg
and invoked with three arguments; (value, key, object).
object
(Object): The source object.[callback]
(Function|...string|string[]): The function called per iteration or property names to omit, specified as individual property names or arrays of property names.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns an object without the omitted properties.
_.omit({ 'name': 'fred', 'age': 40 }, 'age');
// => { 'name': 'fred' }
_.omit({ 'name': 'fred', 'age': 40 }, function(value) {
return typeof value == 'number';
});
// => { 'name': 'fred' }
Creates a two dimensional array of an 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({ 'barney': 36, 'fred': 40 });
// => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
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 a callback is provided it will be executed for each property of object
picking the properties the callback returns truey for. The callback is bound to thisArg
and invoked with three arguments; (value, key, object).
object
(Object): The source object.[callback]
(Function|...string|string[]): The function called per iteration or property names to pick, specified as individual property names or arrays of property names.[thisArg]
(*): Thethis
binding ofcallback
.
(Object): Returns an object composed of the picked properties.
_.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
// => { 'name': 'fred' }
_.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
return key.charAt(0) != '_';
});
// => { 'name': 'fred' }
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 a callback, with each callback execution potentially mutating the accumulator
object. The callback is bound to thisArg
and invoked with four arguments; (accumulator, value, key, object). Callbacks may exit iteration early by explicitly returning false
.
object
(Array|Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[accumulator]
(*): The custom accumulator value.[thisArg]
(*): Thethis
binding ofcallback
.
(*): Returns the accumulated value.
var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8], function(result, num) {
num *= num;
if (num % 2) {
return result.push(num) < 3;
}
});
// => [1, 9, 25]
var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
result[key] = num * 3;
});
// => { 'a': 3, 'b': 6, 'c': 9 }
Creates an array composed of the own enumerable property values of object
.
object
(Object): The object to inspect.
(Array): Returns an array of property values.
_.values({ 'one': 1, 'two': 2, 'three': 3 });
// => [1, 2, 3] (property order is not guaranteed across environments)
Converts the first character of string
to upper case.
string
(string): The string to capitalize.
(string): Returns the capitalized string.
_.capitalize('fred');
// => 'Fred'
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](http://mths.be/he).
When working with HTML you should always quote attribute values to reduce XSS vectors. See [Ryan Grove's article](http://wonko.com/post/html-escaping) for more details.
string
(string): The string to escape.
(string): Returns the escaped string.
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escaped interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters. If a data object is provided the interpolated template string will be returned. Data properties may be accessed as free variables in the template. If a settings object is provided it will override _.templateSettings
for the template.
Note: In the development build, _.template
utilizes sourceURLs for easier debugging. See [HTML5 Rocks' article on sourcemaps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for more details.
For more information on precompiling templates see [Lo-Dash's custom builds documentation](http://lodash.com/custom-builds).
For more information on Chrome extension sandboxes see [Chrome's extensions documentation](http://developer.chrome.com/stable/extensions/sandboxingEval.html).
text
(string): The template text.[data]
(Object): The data object used to populate the text.[options]
(Object): The options object.[options.escape]
(RegExp): The HTML "escape" delimiter.[options.evaluate]
(RegExp): The "evaluate" delimiter.[options.imports]
(Object): An object to import into the template as local variables.[options.interpolate]
(RegExp): The "interpolate" delimiter.[options.sourceURL]
(string): The sourceURL of the template's compiled source.[options.variable]
(string): The data object variable name.
(Function, string): Returns the interpolated string if a data object is provided, else it returns a template function.
// using the "interpolate" delimiter to create a compiled template
var compiled = _.template('hello <%= name %>');
compiled({ 'name': 'fred' });
// => 'hello fred'
// using the HTML "escape" delimiter to escape data property values
_.template('<b><%- value %></b>', { 'value': '<script>' });
// => '<b><script></b>'
// using the "evaluate" delimiter to execute JavaScript and generate HTML
var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
_.template(list, { 'people': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'
// using the ES6 delimiter as an alternative to the default "interpolate" delimiter
_.template('hello ${ name }', { 'name': 'pebbles' });
// => 'hello pebbles'
// using the internal `print` function in "evaluate" delimiters
_.template('<% print("hello " + name); %>!', { 'name': 'barney' });
// => 'hello barney!'
// using a custom template delimiters
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
_.template('hello {{ name }}!', { 'name': 'mustache' });
// => 'hello mustache!'
// using the `imports` option to import jQuery
var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
_.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
// => '<li>fred</li><li>barney</li>'
// 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('hi <%= data.name %>!', null, { 'variable': 'data' });
compiled.source;
// => function(data) {
var __t, __p = '', __e = _.escape;
__p += 'hi ' + ((__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 + '\
};\
');
Removes leading and trailing whitespace or specified characters from string
.
string
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.
(string): Returns the trimmed string.
_.trim(' fred ');
// => 'fred'
_.trim('-_-fred-_-', '_-');
// => 'fred'
Removes leading whitespace or specified characters from string
.
string
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.
(string): Returns the trimmed string.
_.trimLeft(' fred ');
// => 'fred '
_.trimLeft('-_-fred-_-', '_-');
// => 'fred-_-'
Removes trailing whitespace or specified characters from string
.
string
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.
(string): Returns the trimmed string.
_.trimRight(' fred ');
// => ' fred'
_.trimRight('-_-fred-_-', '_-');
// => '-_-fred'
The inverse of _.escape
; this method converts the HTML entities &
, <
, >
, "
, and '
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](http://mths.be/he).
string
(string): The string to unescape.
(string): Returns the unescaped string.
_.unescape('fred, barney & pebbles');
// => 'fred, barney & pebbles'
(unknown): Gets the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00
:00:00 UTC).
var stamp = _.now();
_.defer(function() { console.log(_.now() - stamp); });
// => logs the number of milliseconds it took for the deferred function to be called
Creates a function that returns value
.
value
(*): The value to return from the new function.
(Function): Returns the new function.
var object = { 'name': 'fred' };
var getter = _.constant(object);
getter() === object;
// => true
Produces a callback bound to an optional thisArg
. If func
is a property name the created callback will return the property value for a given element. If func
is an object the created callback will return true
for elements that contain the equivalent object properties, otherwise it will return false
.
_.callback
[func=identity]
(*): The value to convert to a callback.[thisArg]
(*): Thethis
binding of the created callback.[argCount]
(number): The number of arguments the callback accepts.
(Function): Returns a callback function.
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
// wrap to create custom callback shorthands
_.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
return !match ? func(callback, thisArg) : function(object) {
return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
};
});
_.filter(characters, 'age__gt38');
// => [{ 'name': 'fred', 'age': 40 }]
This method returns the first argument provided to it.
value
(*): Any value.
(*): Returns value
.
var object = { 'name': 'fred' };
_.identity(object) === object;
// => true
Creates a "_.where" style function, which performs a deep comparison between a given object and the source
object, returning true
if the given object has equivalent property values, else false
.
source
(Object): The object of property values to match.
(Function): Returns the new function.
var characters = [
{ 'name': 'fred', 'age': 40 },
{ 'name': 'barney', 'age': 36 }
];
var matchesAge = _.matches({ 'age': 36 });
_.filter(characters, matchesAge);
// => [{ 'name': 'barney', 'age': 36 }]
_.find(characters, matchesAge);
// => { 'name': 'barney', 'age': 36 }
Adds function properties of a source object to the destination object. If object
is a function methods will be added to its prototype as well.
[object=lodash]
(Function|Object): object The destination object.source
(Object): The object of functions to add.[options]
(Object): The options object.[options.chain=true]
(boolean): Specify whether the functions added are chainable.
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']
Reverts the '_' variable to its previous value and returns a reference to the lodash
function.
(Function): Returns the lodash
function.
var lodash = _.noConflict();
A no-operation function.
var object = { 'name': 'fred' };
_.noop(object) === undefined;
// => true
Converts value
to an integer of the specified radix. If radix
is undefined
or 0
a radix
of 10
is used unless the value
is a hexadecimal, in which case a radix
of 16
is used.
Note: This method avoids differences in native ES3 and ES5 parseInt
implementations. See the [ES5 spec](http://es5.github.io/#E) for more details.
value
(string): The value to parse.[radix]
(number): The radix used to interpret the value to parse.
(number): Returns the new integer value.
_.parseInt('08');
// => 8
Creates a "_.pluck" style function, which returns the key
value of a given object.
key
(string): The name of the property to retrieve.
(Function): Returns the new function.
var characters = [
{ 'name': 'fred', 'age': 40 },
{ 'name': 'barney', 'age': 36 }
];
var getName = _.property('name');
_.map(characters, getName);
// => ['barney', 'fred']
_.sortBy(characters, getName);
// => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
Produces a random number between min
and max
(inclusive). If only one argument is provided a number between 0
and the given number will be returned. If floating
is truey or either min
or max
are floats a floating-point number will be returned instead of an integer.
[min=0]
(number): The minimum possible value.[max=1]
(number): The maximum possible value.[floating=false]
(boolean): Specify returning a floating-point number.
(number): Returns a random number.
_.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
Resolves the value of property key
on object
. If key
is a function it will be invoked with the this
binding of object
and its result returned, else the property value is returned. If object
is null
or undefined
then undefined
is returned. If a default value is provided it will be returned if the property value resolves to undefined
.
object
(Object): The object to inspect.key
(string): The name of the property to resolve.[defaultValue]
(*): The value returned if the property value resolves toundefined
.
(*): Returns the resolved value.
var object = {
'name': 'fred',
'age': function() {
return 40;
}
};
_.result(object, 'name');
// => 'fred'
_.result(object, 'age');
// => 40
_.result(object, 'employer', 'slate');
// => 'slate'
Create a new lodash
function using the given context object.
[context=root]
(Object): The context object.
(Function): Returns a new lodash
function.
Executes the callback 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]
(*): Thethis
binding ofcallback
.
(Array): Returns an 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
Generates a unique ID. If prefix
is provided 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'
A reference to the lodash
function.
(string): The semantic version number.
(Object): An object used to flag environments features.
(boolean): Detect if an arguments
object's [[Class]] is resolvable (all but Firefox < 4
, IE < 9
).
(boolean): Detect if arguments
objects are Object
objects (all but Narwhal and Opera < 10.5
).
(boolean): Detect if name
or message
properties of Error.prototype
are enumerable by default. (IE < 9
, Safari < 5.1
)
(boolean): Detect if prototype
properties are enumerable by default.
Firefox < 3.6
, Opera > 9.50
- Opera < 11.60
, and Safari < 5.1
(if the prototype or a property on the prototype has been set) incorrectly sets a function's prototype
property [[Enumerable]] value to true
.
(boolean): Detect if functions can be decompiled by Function#toString
(all but PS3 and older Opera mobile browsers & avoided in Windows 8
apps).
(boolean): Detect if Function#name
is supported (all but IE).
(boolean): Detect if arguments
object indexes are non-enumerable (Firefox < 4
, IE < 9
, PhantomJS, Safari < 5.1
).
(boolean): Detect if properties shadowing those on Object.prototype
are non-enumerable.
In IE < 9
an objects own properties, shadowing non-enumerable ones, are made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug).
(boolean): Detect if own properties are iterated after inherited properties (all but IE < 9
).
(boolean): Detect if Array#shift
and Array#splice
augment array-like objects correctly.
Firefox < 10
, IE compatibility mode, and IE < 9
have buggy Array shift()
and splice()
functions that fail to remove the last element, value[0]
, of array-like objects even though the length
property is set to 0
. The shift()
method is buggy in IE 8
compatibility mode, while splice()
is buggy regardless of mode in IE < 9
and buggy in compatibility mode in IE 9
.
(boolean): Detect lack of support for accessing string characters by index.
IE < 8
can't access characters by index and IE 8
can only access characters by index on string literals.
(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.
(Object): Used to import variables into the compiled template.