new _(value) → {Object}
Creates a lodash
object which wraps the given value to enable 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
, countBy
, createCallback
, curry
, debounce
,
defaults
, defer
, delay
, difference
, filter
, flatten
, forEach
,
forEachRight
, forIn
, forInRight
, forOwn
, forOwnRight
, functions
,
groupBy
, indexBy
, initial
, intersection
, invert
, invoke
, keys
,
map
, max
, memoize
, merge
, min
, object
, omit
, once
, pairs
,
partial
, partialRight
, pick
, pluck
, 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
, and zip
The non-chainable wrapper functions are:
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
, parseInt
, pop
, random
, reduce
,
reduceRight
, result
, shift
, size
, some
, sortedIndex
, runInContext
,
template
, unescape
, uniqueId
, and value
The wrapper functions first
and last
return wrapped values when n
is
provided, otherwise they return unwrapped values.
Example
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
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to wrap in a |
Returns:
Returns a lodash
instance.
- Type
- Object
Members
(static) chain
Enables method chaining on the wrapper object.
Example
var sum = _([1, 2, 3])
.chain()
.reduce(function(sum, num) { return sum + num; })
.value()
// => 6`
(static) countBy
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
.
Example
_.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 }
(static) defaults :function
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.
Type:
- function
Example
var food = { 'name': 'apple' };
_.defaults(food, { 'name': 'banana', 'type': 'fruit' });
// => { 'name': 'apple', 'type': 'fruit' }
(static) extend :function
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).
Type:
- function
Example
_.assign({ 'name': 'moe' }, { 'age': 40 });
// => { 'name': 'moe', 'age': 40 }
var defaults = _.partialRight(_.assign, function(a, b) {
return typeof a == 'undefined' ? b : a;
});
var food = { 'name': 'apple' };
defaults(food, { 'name': 'banana', 'type': 'fruit' });
// => { 'name': 'apple', 'type': 'fruit' }
(static) forIn :function
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
.
Type:
- function
Example
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function() {
console.log('Woof, woof!');
};
_.forIn(new Dog('Dagny'), function(value, key) {
console.log(key);
});
// => logs 'bark' and 'name' (property order is not guaranteed across environments)
(static) forOwn :function
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
.
Type:
- function
Example
_.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)
(static) groupBy
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
Example
_.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'] }
(static) indexBy
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
.
Example
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(stooges, function(key) { this.fromCharCode(key.code); }, String);
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
(static) isArray :function
Checks if value
is an array.
Type:
- function
Example
(function() { return _.isArray(arguments); })();
// => false
_.isArray([1, 2, 3]);
// => true
(static) isPlainObject
Checks if value
is an object created by the Object
constructor.
Example
function Stooge(name, age) {
this.name = name;
this.age = age;
}
_.isPlainObject(new Stooge('moe', 40));
// => false
_.isPlainObject([1, 2, 3]);
// => false
_.isPlainObject({ 'name': 'moe', 'age': 40 });
// => true
(static) keys
Creates an array composed of the own enumerable property names of an object.
Example
_.keys({ 'one': 1, 'two': 2, 'three': 3 });
// => ['one', 'two', 'three'] (property order is not guaranteed across environments)
(static) parseInt
Converts the given value
into 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 http://es5.github.io/#E.
Example
_.parseInt('08');
// => 8
(static) pluck :function
Retrieves the value of a specified property from all elements in the collection
.
Type:
- function
Example
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
_.pluck(stooges, 'name');
// => ['moe', 'larry']
(static) support :Object
An object used to flag environments features.
Type:
- Object
(static) toString
Produces the toString
result of the wrapped value.
Example
_([1, 2, 3]).toString();
// => '1,2,3'
(static) valueOf
Extracts the wrapped value.
Example
_([1, 2, 3]).valueOf();
// => [1, 2, 3]
(static) where :function
Performs a deep comparison of each element in a collection
to the given
properties
object, returning an array of all elements that have equivalent
property values.
Type:
- function
Example
var stooges = [
{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
{ 'name': 'moe', 'age': '40', 'quotes': ['Spread out!', 'You knucklehead!'] }
];
_.where(stooges, { 'age': 40 });
// => [{ 'name': 'moe', 'age': '40', 'quotes': ['Spread out!', 'You knucklehead!'] }]
_.where(stooges, { 'quotes': ['Poifect!'] });
// => [{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }]
Methods
(static) after(n, func) → {function}
Creates a function that executes func
, with the this
binding and
arguments of the created function, only after being called n
times.
Example
var saves = ['profile', 'settings'];
var done = _.after(saves.length, function() {
console.log('Done saving!');
});
_.forEach(saves, function(type) {
asyncSave({ 'type': type, 'complete': done });
});
// => logs 'Done saving!', after all saves have completed
Parameters:
Name | Type | Description |
---|---|---|
n |
number | The number of times the function must be called before
|
func |
function | The function to restrict. |
Returns:
Returns the new restricted function.
- Type
- function
(static) all(collection, callbackopt, thisArgopt) → {boolean}
Checks if the given 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
.
Example
_.every([true, 1, null, 'yes'], Boolean);
// => false
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
// using "_.pluck" callback shorthand
_.every(stooges, 'age');
// => true
// using "_.where" callback shorthand
_.every(stooges, { 'age': 50 });
// => false
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns true
if all elements passed the callback check,
else false
.
- Type
- boolean
(static) any(collection, callbackopt, thisArgopt) → {boolean}
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
.
Example
_.some([null, 0, 'yes', false], Boolean);
// => true
var food = [
{ 'name': 'apple', 'organic': false, 'type': 'fruit' },
{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
];
// using "_.pluck" callback shorthand
_.some(food, 'organic');
// => true
// using "_.where" callback shorthand
_.some(food, { 'type': 'meat' });
// => false
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns true
if any element passed the callback check,
else false
.
- Type
- boolean
(static) at(collection, …indexopt) → {Array}
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.
Example
_.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
// => ['a', 'c', 'e']
_.at(['moe', 'larry', 'curly'], 0, 2);
// => ['moe', 'curly']
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
|
index |
number | Array.<number> | string | Array.<string> |
<optional> <repeatable> |
The indexes of |
Returns:
Returns a new array of elements corresponding to the provided indexes.
- Type
- Array
(static) bind(func, thisArgopt, …argopt) → {function}
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.
Example
var func = function(greeting) {
return greeting + ' ' + this.name;
};
func = _.bind(func, { 'name': 'moe' }, 'hi');
func();
// => 'hi moe'
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function | The function to bind. |
|
thisArg |
* |
<optional> |
The |
arg |
* |
<optional> <repeatable> |
Arguments to be partially applied. |
Returns:
Returns the new bound function.
- Type
- function
(static) bindAll(object, …methodNameopt) → {Object}
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.
Example
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
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The object to bind and assign the bound methods to. |
|
methodName |
string |
<optional> <repeatable> |
The object method names to bind, specified as individual method names or arrays of method names. |
Returns:
Returns object
.
- Type
- Object
(static) bindKey(object, key, …argopt) → {function}
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 http://michaux.ca/articles/lazy-function-definition-pattern.
Example
var object = {
'name': 'moe',
'greet': function(greeting) {
return greeting + ' ' + this.name;
}
};
var func = _.bindKey(object, 'greet', 'hi');
func();
// => 'hi moe'
object.greet = function(greeting) {
return greeting + ', ' + this.name + '!';
};
func();
// => 'hi, moe!'
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The object the method belongs to. |
|
key |
string | The key of the method. |
|
arg |
* |
<optional> <repeatable> |
Arguments to be partially applied. |
Returns:
Returns the new bound function.
- Type
- function
(static) chain(value) → {Object}
Creates a lodash
object that wraps the given value
.
Example
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 },
{ 'name': 'curly', 'age': 60 }
];
var youngest = _.chain(stooges)
.sortBy(function(stooge) { return stooge.age; })
.map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
.first();
// => 'moe is 40'
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to wrap. |
Returns:
Returns the wrapper object.
- Type
- Object
(static) clone(value, deepopt, callbackopt, thisArgopt) → {*}
Creates a clone of value
. If deep
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).
Example
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
var shallow = _.clone(stooges);
shallow[0] === stooges[0];
// => true
var deep = _.clone(stooges, true);
deep[0] === stooges[0];
// => false
_.mixin({
'clone': _.partialRight(_.clone, function(value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
})
});
var clone = _.clone(document.body);
clone.childNodes.length;
// => 0
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
value |
* | The value to clone. |
||
deep |
boolean |
<optional> |
false | A flag to indicate a deep clone. |
callback |
function |
<optional> |
The function to customize cloning values. |
|
thisArg |
* |
<optional> |
The |
Returns:
Returns the cloned value
.
- Type
- *
(static) cloneDeep(value, callbackopt, thisArgopt) → {*}
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 http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
Example
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
var deep = _.cloneDeep(stooges);
deep[0] === stooges[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
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
value |
* | The value to deep clone. |
|
callback |
function |
<optional> |
The function to customize cloning values. |
thisArg |
* |
<optional> |
The |
Returns:
Returns the deep cloned value
.
- Type
- *
(static) collect(collection, callbackopt, thisArgopt) → {Array}
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
.
Example
_.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 stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
// using "_.pluck" callback shorthand
_.map(stooges, 'name');
// => ['moe', 'larry']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns a new array of the results of each callback
execution.
- Type
- Array
(static) compact(array) → {Array}
Creates an array with all falsey values removed. The values false
, null
,
0
, ""
, undefined
, and NaN
are all falsey.
Example
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to compact. |
Returns:
Returns a new array of filtered values.
- Type
- Array
(static) compose(…funcopt) → {function}
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.
Example
var realNameMap = {
'curly': 'jerome'
};
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('curly');
// => 'Hiya Jerome!'
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function |
<optional> <repeatable> |
Functions to compose. |
Returns:
Returns the new composed function.
- Type
- function
(static) createCallback(funcopt, thisArgopt, argCountopt) → {function}
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
.
Example
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
// 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(stooges, 'age__gt45');
// => [{ 'name': 'larry', 'age': 50 }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
* |
<optional> |
identity | The value to convert to a callback. |
thisArg |
* |
<optional> |
The |
|
argCount |
number |
<optional> |
The number of arguments the callback accepts. |
Returns:
Returns a callback function.
- Type
- function
(static) curry(func, arityopt) → {function}
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.
Example
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
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
function | The function to curry. |
||
arity |
number |
<optional> |
func.length | The arity of |
Returns:
Returns the new curried function.
- Type
- function
(static) debounce(func, wait, optionsopt) → {function}
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.
Example
// 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);
Parameters:
Name | Type | Attributes | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
func |
function | The function to debounce. |
|||||||||||||||||||||
wait |
number | The number of milliseconds to delay. |
|||||||||||||||||||||
options |
Object |
<optional> |
The options object. Properties
|
Returns:
Returns the new debounced function.
- Type
- function
(static) defer(func, …argopt) → {number}
Defers executing the func
function until the current call stack has cleared.
Additional arguments will be provided to func
when it is invoked.
Example
_.defer(function() { console.log('deferred'); });
// returns from the function before 'deferred' is logged
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function | The function to defer. |
|
arg |
* |
<optional> <repeatable> |
Arguments to invoke the function with. |
Returns:
Returns the timer id.
- Type
- number
(static) delay(func, wait, …argopt) → {number}
Executes the func
function after wait
milliseconds. Additional arguments
will be provided to func
when it is invoked.
Example
var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
// => 'logged later' (Appears after one second.)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function | The function to delay. |
|
wait |
number | The number of milliseconds to delay execution. |
|
arg |
* |
<optional> <repeatable> |
Arguments to invoke the function with. |
Returns:
Returns the timer id.
- Type
- number
(static) difference(array, …arrayopt) → {Array}
Creates an array excluding all values of the provided arrays using strict
equality for comparisons, i.e. ===
.
Example
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
// => [1, 3, 4]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array | The array to process. |
|
array |
Array |
<optional> <repeatable> |
The arrays of values to exclude. |
Returns:
Returns a new array of filtered values.
- Type
- Array
(static) each(collection, callbackopt, thisArgopt) → {Array|Object|string}
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
.
Example
_([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)
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function |
<optional> |
identity | The function called per iteration. |
thisArg |
* |
<optional> |
The |
Returns:
Returns collection
.
- Type
- Array | Object | string
(static) eachRight(collection, callbackopt, thisArgopt) → {Array|Object|string}
This method is like _.forEach
except that it iterates over elements
of a collection
from right to left.
Example
_([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
// => logs each number from right to left and returns '3,2,1'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function |
<optional> |
identity | The function called per iteration. |
thisArg |
* |
<optional> |
The |
Returns:
Returns collection
.
- Type
- Array | Object | string
(static) escape(string) → {string}
Converts the characters &
, <
, >
, "
, and '
in string
to their
corresponding HTML entities.
Example
_.escape('Moe, Larry & Curly');
// => 'Moe, Larry & Curly'
Parameters:
Name | Type | Description |
---|---|---|
string |
string | The string to escape. |
Returns:
Returns the escaped string.
- Type
- string
(static) findIndex(array, callbackopt, thisArgopt) → {number}
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.
Example
_.findIndex(['apple', 'banana', 'beet'], function(food) {
return /^b/.test(food);
});
// => 1
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to search. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the index of the found element, else -1
.
- Type
- number
(static) findKey(object, callbackopt, thisArgopt) → {string|undefined}
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.
Example
_.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
return num % 2 == 0;
});
// => 'b' (property order is not guaranteed across environments)
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to search. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the key of the found element, else undefined
.
- Type
- string | undefined
(static) findLast(collection, callbackopt, thisArgopt) → {*}
This method is like _.find
except that it iterates over elements
of a collection
from right to left.
Example
_.findLast([1, 2, 3, 4], function(num) {
return num % 2 == 1;
});
// => 3
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the found element, else undefined
.
- Type
- *
(static) findLastIndex(array, callbackopt, thisArgopt) → {number}
This method is like _.findIndex
except that it iterates over elements
of a collection
from right to left.
Example
_.findLastIndex(['apple', 'banana', 'beet'], function(food) {
return /^b/.test(food);
});
// => 2
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to search. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the index of the found element, else -1
.
- Type
- number
(static) findLastKey(object, callbackopt, thisArgopt) → {string|undefined}
This method is like _.findKey
except that it iterates over elements
of a collection
in the opposite order.
Example
_.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
return num % 2 == 1;
});
// => returns `c`, assuming `_.findKey` returns `a`
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to search. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the key of the found element, else undefined
.
- Type
- string | undefined
(static) flatten(array, isShallowopt, callbackopt, thisArgopt) → {Array}
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
.
Example
_.flatten([1, [2], [3, [[4]]]]);
// => [1, 2, 3, 4];
_.flatten([1, [2], [3, [[4]]]], true);
// => [1, 2, 3, [[4]]];
var stooges = [
{ 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
{ 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
];
// using "_.pluck" callback shorthand
_.flatten(stooges, 'quotes');
// => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to flatten. |
||
isShallow |
boolean |
<optional> |
false | A flag to restrict flattening to a single level. |
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns a new flattened array.
- Type
- Array
(static) foldr(collection, callbackopt, accumulatoropt, thisArgopt) → {*}
This method is like _.reduce
except that it iterates over elements
of a collection
from right to left.
Example
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]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function |
<optional> |
identity | The function called per iteration. |
accumulator |
* |
<optional> |
Initial value of the accumulator. |
|
thisArg |
* |
<optional> |
The |
Returns:
Returns the accumulated value.
- Type
- *
(static) forInRight(object, callbackopt, thisArgopt) → {Object}
This method is like _.forIn
except that it iterates over elements
of a collection
in the opposite order.
Example
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function() {
console.log('Woof, woof!');
};
_.forInRight(new Dog('Dagny'), function(value, key) {
console.log(key);
});
// => logs 'name' and 'bark' assuming `_.forIn ` logs 'bark' and 'name'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
callback |
function |
<optional> |
identity | The function called per iteration. |
thisArg |
* |
<optional> |
The |
Returns:
Returns object
.
- Type
- Object
(static) forOwnRight(object, callbackopt, thisArgopt) → {Object}
This method is like _.forOwn
except that it iterates over elements
of a collection
in the opposite order.
Example
_.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'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
callback |
function |
<optional> |
identity | The function called per iteration. |
thisArg |
* |
<optional> |
The |
Returns:
Returns object
.
- Type
- Object
(static) has(object, property) → {boolean}
Checks if the specified object property
exists and is a direct property,
instead of an inherited property.
Example
_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
// => true
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to check. |
property |
string | The property to check for. |
Returns:
Returns true
if key is a direct property, else false
.
- Type
- boolean
(static) identity(value) → {*}
This method returns the first argument provided to it.
Example
var moe = { 'name': 'moe' };
moe === _.identity(moe);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | Any value. |
Returns:
Returns value
.
- Type
- *
(static) include(collection, target, fromIndexopt) → {boolean}
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.
Example
_.contains([1, 2, 3], 1);
// => true
_.contains([1, 2, 3], 1, 2);
// => false
_.contains({ 'name': 'moe', 'age': 40 }, 'moe');
// => true
_.contains('curly', 'ur');
// => true
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
target |
* | The value to check for. |
||
fromIndex |
number |
<optional> |
0 | The index to search from. |
Returns:
Returns true
if the target
element is found, else false
.
- Type
- boolean
(static) indexOf(array, value, fromIndexopt) → {number}
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.
Example
_.indexOf([1, 2, 3, 1, 2, 3], 2);
// => 1
_.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
// => 4
_.indexOf([1, 1, 2, 2, 3, 3], 2, true);
// => 2
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to search. |
||
value |
* | The value to search for. |
||
fromIndex |
boolean | number |
<optional> |
0 | The index to search from or |
Returns:
Returns the index of the matched value or -1
.
- Type
- number
(static) initial(array, callbackopt, thisArgopt) → {Array}
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
.
Example
_.initial([1, 2, 3]);
// => [1, 2]
_.initial([1, 2, 3], 2);
// => [1]
_.initial([1, 2, 3], function(num) {
return num > 1;
});
// => [1]
var food = [
{ 'name': 'beet', 'organic': false },
{ 'name': 'carrot', 'organic': true }
];
// using "_.pluck" callback shorthand
_.initial(food, 'organic');
// => [{ 'name': 'beet', 'organic': false }]
var food = [
{ 'name': 'banana', 'type': 'fruit' },
{ 'name': 'beet', 'type': 'vegetable' },
{ 'name': 'carrot', 'type': 'vegetable' }
];
// using "_.where" callback shorthand
_.initial(food, { 'type': 'vegetable' });
// => [{ 'name': 'banana', 'type': 'fruit' }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
callback |
function | Object | number | string |
<optional> |
1 | 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 |
* |
<optional> |
The |
Returns:
Returns a slice of array
.
- Type
- Array
(static) intersection(…arrayopt) → {Array}
Creates an array of unique values present in all provided arrays using
strict equality for comparisons, i.e. ===
.
Example
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
// => [1, 2]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array |
<optional> <repeatable> |
The arrays to inspect. |
Returns:
Returns an array of composite values.
- Type
- Array
(static) invert(object) → {Object}
Creates an object composed of the inverted keys and values of the given object.
Example
_.invert({ 'first': 'moe', 'second': 'larry' });
// => { 'moe': 'first', 'larry': 'second' }
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to invert. |
Returns:
Returns the created inverted object.
- Type
- Object
(static) invoke(collection, methodName, …argopt) → {Array}
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
.
Example
_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
// => [[1, 5, 7], [1, 2, 3]]
_.invoke([123, 456], String.prototype.split, '');
// => [['1', '2', '3'], ['4', '5', '6']]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
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. |
|
arg |
* |
<optional> <repeatable> |
Arguments to invoke the method with. |
Returns:
Returns a new array of the results of each invoked method.
- Type
- Array
(static) isArguments(value) → {boolean}
Checks if value
is an arguments
object.
Example
(function() { return _.isArguments(arguments); })(1, 2, 3);
// => true
_.isArguments([1, 2, 3]);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is an arguments
object, else false
.
- Type
- boolean
(static) isBoolean(value) → {boolean}
Checks if value
is a boolean value.
Example
_.isBoolean(null);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is a boolean value, else false
.
- Type
- boolean
(static) isDate(value) → {boolean}
Checks if value
is a date.
Example
_.isDate(new Date);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is a date, else false
.
- Type
- boolean
(static) isElement(value) → {boolean}
Checks if value
is a DOM element.
Example
_.isElement(document.body);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is a DOM element, else false
.
- Type
- boolean
(static) isEmpty(value) → {boolean}
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".
Example
_.isEmpty([1, 2, 3]);
// => false
_.isEmpty({});
// => true
_.isEmpty('');
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
Array | Object | string | The value to inspect. |
Returns:
Returns true
if the value
is empty, else false
.
- Type
- boolean
(static) isEqual(a, b, callbackopt, thisArgopt) → {boolean}
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).
Example
var moe = { 'name': 'moe', 'age': 40 };
var copy = { 'name': 'moe', 'age': 40 };
moe == copy;
// => false
_.isEqual(moe, 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
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
a |
* | The value to compare. |
|
b |
* | The other value to compare. |
|
callback |
function |
<optional> |
The function to customize comparing values. |
thisArg |
* |
<optional> |
The |
Returns:
Returns true
if the values are equivalent, else false
.
- Type
- boolean
(static) isFinite(value) → {boolean}
Checks if value
is, or can be coerced to, a finite number.
Note: This is not the same as native isFinite
which will return true for
booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
Example
_.isFinite(-101);
// => true
_.isFinite('10');
// => true
_.isFinite(true);
// => false
_.isFinite('');
// => false
_.isFinite(Infinity);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is finite, else false
.
- Type
- boolean
(static) isFunction(value) → {boolean}
Checks if value
is a function.
Example
_.isFunction(_);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is a function, else false
.
- Type
- boolean
(static) isNaN(value) → {boolean}
Checks if value
is NaN
.
Note: This is not the same as native isNaN
which will return true
for
undefined
and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
Example
_.isNaN(NaN);
// => true
_.isNaN(new Number(NaN));
// => true
isNaN(undefined);
// => true
_.isNaN(undefined);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is NaN
, else false
.
- Type
- boolean
(static) isNull(value) → {boolean}
Checks if value
is null
.
Example
_.isNull(null);
// => true
_.isNull(undefined);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is null
, else false
.
- Type
- boolean
(static) isNumber(value) → {boolean}
Checks if value
is a number.
Note: NaN
is considered a number. See http://es5.github.io/#x8.5.
Example
_.isNumber(8.4 * 5);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is a number, else false
.
- Type
- boolean
(static) isObject(value) → {boolean}
Checks if value
is the language type of Object.
(e.g. arrays, functions, objects, regexes, new Number(0)
, and new String('')
)
Example
_.isObject({});
// => true
_.isObject([1, 2, 3]);
// => true
_.isObject(1);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is an object, else false
.
- Type
- boolean
(static) isRegExp(value) → {boolean}
Checks if value
is a regular expression.
Example
_.isRegExp(/moe/);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is a regular expression, else false
.
- Type
- boolean
(static) isString(value) → {boolean}
Checks if value
is a string.
Example
_.isString('moe');
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is a string, else false
.
- Type
- boolean
(static) isUndefined(value) → {boolean}
Checks if value
is undefined
.
Example
_.isUndefined(void 0);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if the value
is undefined
, else false
.
- Type
- boolean
(static) last(array, callbackopt, thisArgopt) → {*}
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
.
Example
_.last([1, 2, 3]);
// => 3
_.last([1, 2, 3], 2);
// => [2, 3]
_.last([1, 2, 3], function(num) {
return num > 1;
});
// => [2, 3]
var food = [
{ 'name': 'beet', 'organic': false },
{ 'name': 'carrot', 'organic': true }
];
// using "_.pluck" callback shorthand
_.last(food, 'organic');
// => [{ 'name': 'carrot', 'organic': true }]
var food = [
{ 'name': 'banana', 'type': 'fruit' },
{ 'name': 'beet', 'type': 'vegetable' },
{ 'name': 'carrot', 'type': 'vegetable' }
];
// using "_.where" callback shorthand
_.last(food, { 'type': 'vegetable' });
// => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array | The array to query. |
|
callback |
function | Object | number | string |
<optional> |
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 |
* |
<optional> |
The |
Returns:
Returns the last element(s) of array
.
- Type
- *
(static) lastIndexOf(array, value, fromIndexopt) → {number}
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.
Example
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
// => 4
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
// => 1
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to search. |
||
value |
* | The value to search for. |
||
fromIndex |
number |
<optional> |
array.length-1 | The index to search from. |
Returns:
Returns the index of the matched value or -1
.
- Type
- number
(static) max(collection, callbackopt, thisArgopt) → {*}
Retrieves the maximum value of an array. If a callback is provided it
will be executed for each value in the array to generate the criterion by
which the value is ranked. The callback is bound to thisArg
and invoked
with three arguments; (value, index, collection).
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
.
Example
_.max([4, 2, 8, 6]);
// => 8
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
_.max(stooges, function(stooge) { return stooge.age; });
// => { 'name': 'larry', 'age': 50 };
// using "_.pluck" callback shorthand
_.max(stooges, 'age');
// => { 'name': 'larry', 'age': 50 };
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the maximum value.
- Type
- *
(static) memoize(func, resolveropt) → {function}
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.
Example
var fibonacci = _.memoize(function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
var data = {
'moe': { 'name': 'moe', 'age': 40 },
'curly': { 'name': 'curly', 'age': 60 }
};
// modifying the result cache
var stooge = _.memoize(function(name) { return data[name]; }, _.identity);
stooge('curly');
// => { 'name': 'curly', 'age': 60 }
stooge.cache.curly.name = 'jerome';
stooge('curly');
// => { 'name': 'jerome', 'age': 60 }
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function | The function to have its output memoized. |
|
resolver |
function |
<optional> |
A function used to resolve the cache key. |
Returns:
Returns the new memoizing function.
- Type
- function
(static) merge(object, …sourceopt, callbackopt, thisArgopt) → {Object}
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).
Example
var names = {
'stooges': [
{ 'name': 'moe' },
{ 'name': 'larry' }
]
};
var ages = {
'stooges': [
{ 'age': 40 },
{ 'age': 50 }
]
};
_.merge(names, ages);
// => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] }
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] }
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The destination object. |
|
source |
Object |
<optional> <repeatable> |
The source objects. |
callback |
function |
<optional> |
The function to customize merging properties. |
thisArg |
* |
<optional> |
The |
Returns:
Returns the destination object.
- Type
- Object
(static) methods(object) → {Array}
Creates a sorted array of property names of all enumerable properties,
own and inherited, of object
that have function values.
Example
_.functions(_);
// => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to inspect. |
Returns:
Returns an array of property names that have function values.
- Type
- Array
(static) min(collection, callbackopt, thisArgopt) → {*}
Retrieves the minimum value of an array. If a callback is provided it
will be executed for each value in the array to generate the criterion by
which the value is ranked. The callback is bound to thisArg
and invoked
with three arguments; (value, index, collection).
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
.
Example
_.min([4, 2, 8, 6]);
// => 2
var stooges = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
_.min(stooges, function(stooge) { return stooge.age; });
// => { 'name': 'moe', 'age': 40 };
// using "_.pluck" callback shorthand
_.min(stooges, 'age');
// => { 'name': 'moe', 'age': 40 };
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the minimum value.
- Type
- *
(static) mixin(object, object)
Adds function properties of a source object to the lodash
function and
chainable wrapper.
Example
_.mixin({
'capitalize': function(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
});
_.capitalize('moe');
// => 'Moe'
_('moe').capitalize();
// => 'Moe'
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object of function properties to add to |
object |
Object | The object of function properties to add to |
(static) noConflict() → {function}
Reverts the '_' variable to its previous value and returns a reference to
the lodash
function.
Example
var lodash = _.noConflict();
Returns:
Returns the lodash
function.
- Type
- function
(static) object(keys, valuesopt) → {Object}
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
.
Example
_.zipObject(['moe', 'larry'], [30, 40]);
// => { 'moe': 30, 'larry': 40 }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
keys |
Array | The array of keys. |
||
values |
Array |
<optional> |
[] | The array of values. |
Returns:
Returns an object composed of the given keys and corresponding values.
- Type
- Object
(static) omit(object, callbackopt, thisArgopt) → {Object}
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).
Example
_.omit({ 'name': 'moe', 'age': 40 }, 'age');
// => { 'name': 'moe' }
_.omit({ 'name': 'moe', 'age': 40 }, function(value) {
return typeof value == 'number';
});
// => { 'name': 'moe' }
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The source object. |
|
callback |
function | string | Array.<string> |
<optional> |
The properties to omit or the function called per iteration. |
thisArg |
* |
<optional> |
The |
Returns:
Returns an object without the omitted properties.
- Type
- Object
(static) once(func) → {function}
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.
Example
var initialize = _.once(createApplication);
initialize();
initialize();
// `initialize` executes `createApplication` once
Parameters:
Name | Type | Description |
---|---|---|
func |
function | The function to restrict. |
Returns:
Returns the new restricted function.
- Type
- function
(static) pairs(object) → {Array}
Creates a two dimensional array of an object's key-value pairs,
i.e. [[key1, value1], [key2, value2]]
.
Example
_.pairs({ 'moe': 30, 'larry': 40 });
// => [['moe', 30], ['larry', 40]] (property order is not guaranteed across environments)
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to inspect. |
Returns:
Returns new array of key-value pairs.
- Type
- Array
(static) partial(func, …argopt) → {function}
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.
Example
var greet = function(greeting, name) { return greeting + ' ' + name; };
var hi = _.partial(greet, 'hi');
hi('moe');
// => 'hi moe'
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function | The function to partially apply arguments to. |
|
arg |
* |
<optional> <repeatable> |
Arguments to be partially applied. |
Returns:
Returns the new partially applied function.
- Type
- function
(static) partialRight(func, …argopt) → {function}
This method is like _.partial
except that partial
arguments are
appended to those provided to the new function.
Example
var defaultsDeep = _.partialRight(_.merge, _.defaults);
var options = {
'variable': 'data',
'imports': { 'jq': $ }
};
defaultsDeep(options, _.templateSettings);
options.variable
// => 'data'
options.imports
// => { '_': _, 'jq': $ }
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function | The function to partially apply arguments to. |
|
arg |
* |
<optional> <repeatable> |
Arguments to be partially applied. |
Returns:
Returns the new partially applied function.
- Type
- function
(static) pick(object, callbackopt, thisArgopt) → {Object}
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).
Example
_.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
// => { 'name': 'moe' }
_.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
return key.charAt(0) != '_';
});
// => { 'name': 'moe' }
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The source object. |
|
callback |
function | string | Array.<string> |
<optional> |
The function called per iteration or property names to pick, specified as individual property names or arrays of property names. |
thisArg |
* |
<optional> |
The |
Returns:
Returns an object composed of the picked properties.
- Type
- Object
(static) pull(array, …valueopt) → {Array}
Removes all provided values from the given array using strict equality for
comparisons, i.e. ===
.
Example
var array = [1, 2, 3, 1, 2, 3];
_.pull(array, 2, 3);
console.log(array);
// => [1, 1]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array | The array to modify. |
|
value |
* |
<optional> <repeatable> |
The values to remove. |
Returns:
Returns array
.
- Type
- Array
(static) random(minopt, maxopt) → {number}
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.
Example
_.random(0, 5);
// => a number between 0 and 5
_.random(5);
// => also a number between 0 and 5
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
min |
number |
<optional> |
0 | The minimum possible value. |
max |
number |
<optional> |
1 | The maximum possible value. |
Returns:
Returns a random number.
- Type
- number
(static) range(startopt, end, stepopt) → {Array}
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.
Example
_.range(10);
// => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
// => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
// => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
// => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(1, 4, 0);
// => [1, 1, 1]
_.range(0);
// => []
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
start |
number |
<optional> |
0 | The start of the range. |
end |
number | The end of the range. |
||
step |
number |
<optional> |
1 | The value to increment or decrement by. |
Returns:
Returns a new range array.
- Type
- Array
(static) reject(collection, callbackopt, thisArgopt) → {Array}
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
.
Example
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
// => [1, 3, 5]
var food = [
{ 'name': 'apple', 'organic': false, 'type': 'fruit' },
{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
];
// using "_.pluck" callback shorthand
_.reject(food, 'organic');
// => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
// using "_.where" callback shorthand
_.reject(food, { 'type': 'fruit' });
// => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns a new array of elements that failed the callback check.
- Type
- Array
(static) remove(array, callbackopt, thisArgopt) → {Array}
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
.
Example
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]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to modify. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns a new array of removed elements.
- Type
- Array
(static) result(object, property) → {*}
Resolves the value of property
on object
. If property
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 falsey then undefined
is returned.
Example
var object = {
'cheese': 'crumpets',
'stuff': function() {
return 'nonsense';
}
};
_.result(object, 'cheese');
// => 'crumpets'
_.result(object, 'stuff');
// => 'nonsense'
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to inspect. |
property |
string | The property to get the value of. |
Returns:
Returns the resolved value.
- Type
- *
(static) runInContext(contextopt) → {function}
Create a new lodash
function using the given context
object.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
context |
Object |
<optional> |
root | The context object. |
Returns:
Returns the lodash
function.
- Type
- function
(static) sample(collection, nopt) → {Array}
Retrieves a random element or n
random elements from a collection.
Example
_.sample([1, 2, 3, 4]);
// => 2
_.sample([1, 2, 3, 4], 2);
// => [3, 1]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
collection |
Array | Object | string | The collection to sample. |
|
n |
number |
<optional> |
The number of elements to sample. |
Returns:
Returns the random sample(s) of collection
.
- Type
- Array
(static) select(collection, callbackopt, thisArgopt) → {Array}
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
.
Example
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
// => [2, 4, 6]
var food = [
{ 'name': 'apple', 'organic': false, 'type': 'fruit' },
{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
];
// using "_.pluck" callback shorthand
_.filter(food, 'organic');
// => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
// using "_.where" callback shorthand
_.filter(food, { 'type': 'fruit' });
// => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns a new array of elements that passed the callback check.
- Type
- Array
(static) shuffle(collection) → {Array}
Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
Example
_.shuffle([1, 2, 3, 4, 5, 6]);
// => [4, 1, 6, 3, 5, 2]
Parameters:
Name | Type | Description |
---|---|---|
collection |
Array | Object | string | The collection to shuffle. |
Returns:
Returns a new shuffled collection.
- Type
- Array
(static) size(collection) → {number}
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.
Example
_.size([1, 2]);
// => 2
_.size({ 'one': 1, 'two': 2, 'three': 3 });
// => 3
_.size('curly');
// => 5
Parameters:
Name | Type | Description |
---|---|---|
collection |
Array | Object | string | The collection to inspect. |
Returns:
Returns collection.length
or number of own enumerable properties.
- Type
- number
(static) sortBy(collection, callbackopt, thisArgopt) → {Array}
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 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
.
Example
_.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]
// using "_.pluck" callback shorthand
_.sortBy(['banana', 'strawberry', 'apple'], 'length');
// => ['apple', 'banana', 'strawberry']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to iterate over. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns a new array of sorted elements.
- Type
- Array
(static) sortedIndex(array, value, callbackopt, thisArgopt) → {number}
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
.
Example
_.sortedIndex([20, 30, 50], 40);
// => 2
// using "_.pluck" callback shorthand
_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
// => 2
var dict = {
'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
};
_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return dict.wordToNumber[word];
});
// => 2
_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return this.wordToNumber[word];
}, dict);
// => 2
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to inspect. |
||
value |
* | The value to evaluate. |
||
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns the index at which value
should be inserted
into array
.
- Type
- number
(static) tap(value, interceptor) → {*}
Invokes interceptor
with the value
as the first argument and then
returns value
. The purpose of this method is to "tap into" a method
chain in order to perform operations on intermediate results within
the chain.
Example
_([1, 2, 3, 4])
.filter(function(num) { return num % 2 == 0; })
.tap(function(array) { console.log(array); })
.map(function(num) { return num * num; })
.value();
// => // [2, 4] (logged)
// => [4, 16]
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to provide to |
interceptor |
function | The function to invoke. |
Returns:
Returns value
.
- Type
- *
(static) template(text, data, optionsopt, sourceURLopt, variableopt) → {function|string}
A micro-templating method that handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code.
Note: In the development build, _.template
utilizes sourceURLs for easier
debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
For more information on precompiling templates see: http://lodash.com/#custom-builds
For more information on Chrome extension sandboxes see: http://developer.chrome.com/stable/extensions/sandboxingEval.html
Example
// using the "interpolate" delimiter to create a compiled template
var compiled = _.template('hello <%= name %>');
compiled({ 'name': 'moe' });
// => 'hello moe'
// using the "escape" delimiter to escape HTML in data property values
_.template('<b><%- value %></b>', { 'value': '<script>' });
// => '<b><script></b>'
// using the "evaluate" delimiter to generate HTML
var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
_.template(list, { 'people': ['moe', 'larry'] });
// => '<li>moe</li><li>larry</li>'
// using the ES6 delimiter as an alternative to the default "interpolate" delimiter
_.template('hello ${ name }', { 'name': 'curly' });
// => 'hello curly'
// using the internal `print` function in "evaluate" delimiters
_.template('<% print("hello " + name); %>!', { 'name': 'larry' });
// => 'hello larry!'
// 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 = '<% $.each(people, function(name) { %><li><%= name %></li><% }); %>';
_.template(list, { 'people': ['moe', 'larry'] }, { 'imports': { '$': jQuery });
// => '<li>moe</li><li>larry</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 + '\
};\
');
Parameters:
Name | Type | Attributes | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
text |
string | The template text. |
|||||||||||||||||||||
data |
Object | The data object used to populate the text. |
|||||||||||||||||||||
options |
Object |
<optional> |
The options object. Properties
|
||||||||||||||||||||
sourceURL |
string |
<optional> |
The sourceURL of the template's compiled source. |
||||||||||||||||||||
variable |
string |
<optional> |
The data object variable name. |
Returns:
Returns a compiled function when no data
object
is given, else it returns the interpolated text.
- Type
- function | string
(static) throttle(func, wait, optionsopt) → {function}
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.
Example
// 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
}));
Parameters:
Name | Type | Attributes | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
func |
function | The function to throttle. |
||||||||||||||||
wait |
number | The number of milliseconds to throttle executions to. |
||||||||||||||||
options |
Object |
<optional> |
The options object. Properties
|
Returns:
Returns the new throttled function.
- Type
- function
(static) times(n, callback, thisArgopt) → {Array}
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).
Example
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
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
n |
number | The number of times to execute the callback. |
|
callback |
function | The function called per iteration. |
|
thisArg |
* |
<optional> |
The |
Returns:
Returns an array of the results of each callback
execution.
- Type
- Array
(static) toArray(collection) → {Array}
Converts the collection
to an array.
Example
(function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
// => [2, 3, 4]
Parameters:
Name | Type | Description |
---|---|---|
collection |
Array | Object | string | The collection to convert. |
Returns:
Returns the new converted array.
- Type
- Array
(static) transform(collection, callbackopt, accumulatoropt, thisArgopt) → {*}
An alternative to _.reduce
this method transforms object
to a new
accumulator
object which is the result of running each of its elements
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
.
Example
var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 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 }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
callback |
function |
<optional> |
identity | The function called per iteration. |
accumulator |
* |
<optional> |
The custom accumulator value. |
|
thisArg |
* |
<optional> |
The |
Returns:
Returns the accumulated value.
- Type
- *
(static) unescape(string) → {string}
The inverse of _.escape
this method converts the HTML entities
&
, <
, >
, "
, and '
in string
to their
corresponding characters.
Example
_.unescape('Moe, Larry & Curly');
// => 'Moe, Larry & Curly'
Parameters:
Name | Type | Description |
---|---|---|
string |
string | The string to unescape. |
Returns:
Returns the unescaped string.
- Type
- string
(static) union(…arrayopt) → {Array}
Creates an array of unique values, in order, of the provided arrays using
strict equality for comparisons, i.e. ===
.
Example
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
// => [1, 2, 3, 101, 10]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array |
<optional> <repeatable> |
The arrays to inspect. |
Returns:
Returns an array of composite values.
- Type
- Array
(static) unique(array, isSortedopt, callbackopt, thisArgopt) → {Array}
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
.
Example
_.uniq([1, 2, 1, 3, 1]);
// => [1, 2, 3]
_.uniq([1, 1, 2, 2, 3], true);
// => [1, 2, 3]
_.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
// => ['A', 'b', 'C']
_.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 }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to process. |
||
isSorted |
boolean |
<optional> |
false | A flag to indicate that |
callback |
function | Object | string |
<optional> |
identity | 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 |
* |
<optional> |
The |
Returns:
Returns a duplicate-value-free array.
- Type
- Array
(static) uniqueId(prefixopt) → {string}
Generates a unique ID. If prefix
is provided the ID will be appended to it.
Example
_.uniqueId('contact_');
// => 'contact_104'
_.uniqueId();
// => '105'
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
prefix |
string |
<optional> |
The value to prefix the ID with. |
Returns:
Returns the unique ID.
- Type
- string
(static) unzip(…arrayopt) → {Array}
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.
Example
_.zip(['moe', 'larry'], [30, 40], [true, false]);
// => [['moe', 30, true], ['larry', 40, false]]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array |
<optional> <repeatable> |
Arrays to process. |
Returns:
Returns a new array of grouped elements.
- Type
- Array
(static) values(object) → {Array}
Creates an array composed of the own enumerable property values of object
.
Example
_.values({ 'one': 1, 'two': 2, 'three': 3 });
// => [1, 2, 3] (property order is not guaranteed across environments)
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to inspect. |
Returns:
Returns an array of property values.
- Type
- Array
(static) without(array, …valueopt) → {Array}
Creates an array excluding all provided values using strict equality for
comparisons, i.e. ===
.
Example
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
// => [2, 3, 4]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array | The array to filter. |
|
value |
* |
<optional> <repeatable> |
The values to exclude. |
Returns:
Returns a new array of filtered values.
- Type
- Array
(static) wrap(value, wrapper) → {function}
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.
Example
var hello = function(name) { return 'hello ' + name; };
hello = _.wrap(hello, function(func) {
return 'before, ' + func('moe') + ', after';
});
hello();
// => 'before, hello moe, after'
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to wrap. |
wrapper |
function | The wrapper function. |
Returns:
Returns the new function.
- Type
- function