new _(value) → {Object}
Creates a lodash
object which wraps value
to enable implicit method
chaining. Methods that operate on and return arrays, collections, and
functions can be chained together. Methods that retrieve a single value or
may return a primitive value will automatically end the chain sequence and
return the unwrapped value. Otherwise, the value must be unwrapped with
_#value
.
Explicit chaining, which must be unwrapped with _#value
in all cases,
may be enabled using _.chain
.
The execution of chained methods is lazy, that is, it's deferred until
_#value
is implicitly or explicitly called.
Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion is an optimization to merge iteratee calls; this avoids the creation of intermediate arrays and can greatly reduce the number of iteratee executions. Sections of a chain sequence qualify for shortcut fusion if the section is applied to an array of at least two hundred elements and any iteratees accept only one argument. The heuristic for whether a section qualifies for shortcut fusion is subject to change.
Chaining is supported in custom builds as long as the _#value
method is
directly or indirectly included in the build.
In addition to lodash methods, wrappers have Array
and String
methods.
The wrapper Array
methods are:
concat
, join
, pop
, push
, shift
, sort
, splice
, and unshift
The wrapper String
methods are:
replace
and split
The wrapper methods that support shortcut fusion are:
at
, compact
, drop
, dropRight
, dropWhile
, filter
, find
,
findLast
, head
, initial
, last
, map
, reject
, reverse
, slice
,
tail
, take
, takeRight
, takeRightWhile
, takeWhile
, and toArray
The chainable wrapper methods are:
after
, ary
, assign
, assignIn
, assignInWith
, assignWith
, at
,
before
, bind
, bindAll
, bindKey
, castArray
, chain
, chunk
,
commit
, compact
, concat
, conforms
, constant
, countBy
, create
,
curry
, debounce
, defaults
, defaultsDeep
, defer
, delay
, difference
,
differenceBy
, differenceWith
, drop
, dropRight
, dropRightWhile
,
dropWhile
, fill
, filter
, flatten
, flattenDeep
, flattenDepth
,
flip
, flow
, flowRight
, fromPairs
, functions
, functionsIn
,
groupBy
, initial
, intersection
, intersectionBy
, intersectionWith
,
invert
, invertBy
, invokeMap
, iteratee
, keyBy
, keys
, keysIn
,
map
, mapKeys
, mapValues
, matches
, matchesProperty
, memoize
,
merge
, mergeWith
, method
, methodOf
, mixin
, negate
, nthArg
,
omit
, omitBy
, once
, orderBy
, over
, overArgs
, overEvery
,
overSome
, partial
, partialRight
, partition
, pick
, pickBy
, plant
,
property
, propertyOf
, pull
, pullAll
, pullAllBy
, pullAt
, push
,
range
, rangeRight
, rearg
, reject
, remove
, rest
, reverse
,
sampleSize
, set
, setWith
, shuffle
, slice
, sort
, sortBy
,
splice
, spread
, tail
, take
, takeRight
, takeRightWhile
,
takeWhile
, tap
, throttle
, thru
, toArray
, toPairs
, toPairsIn
,
toPath
, toPlainObject
, transform
, unary
, union
, unionBy
,
unionWith
, uniq
, uniqBy
, uniqWith
, unset
, unshift
, unzip
,
unzipWith
, values
, valuesIn
, without
, wrap
, xor
, xorBy
,
xorWith
, zip
, zipObject
, zipObjectDeep
, and zipWith
The wrapper methods that are not chainable by default are:
add
, attempt
, camelCase
, capitalize
, ceil
, clamp
, clone
,
cloneDeep
, cloneDeepWith
, cloneWith
, deburr
, endsWith
, eq
,
escape
, escapeRegExp
, every
, find
, findIndex
, findKey
, findLast
,
findLastIndex
, findLastKey
, floor
, forEach
, forEachRight
, forIn
,
forInRight
, forOwn
, forOwnRight
, get
, gt
, gte
, has
, hasIn
,
head
, identity
, includes
, indexOf
, inRange
, invoke
, isArguments
,
isArray
, isArrayBuffer
, isArrayLike
, isArrayLikeObject
, isBoolean
,
isBuffer
, isDate
, isElement
, isEmpty
, isEqual
, isEqualWith
,
isError
, isFinite
, isFunction
, isInteger
, isLength
, isMap
,
isMatch
, isMatchWith
, isNaN
, isNative
, isNil
, isNull
, isNumber
,
isObject
, isObjectLike
, isPlainObject
, isRegExp
, isSafeInteger
,
isSet
, isString
, isUndefined
, isTypedArray
, isWeakMap
, isWeakSet
,
join
, kebabCase
, last
, lastIndexOf
, lowerCase
, lowerFirst
,
lt
, lte
, max
, maxBy
, mean
, min
, minBy
, noConflict
, noop
,
now
, pad
, padEnd
, padStart
, parseInt
, pop
, random
, reduce
,
reduceRight
, repeat
, result
, round
, runInContext
, sample
,
shift
, size
, snakeCase
, some
, sortedIndex
, sortedIndexBy
,
sortedLastIndex
, sortedLastIndexBy
, startCase
, startsWith
, subtract
,
sum
, sumBy
, template
, times
, toLower
, toInteger
, toLength
,
toNumber
, toSafeInteger
, toString
, toUpper
, trim
, trimEnd
,
trimStart
, truncate
, unescape
, uniqueId
, upperCase
, upperFirst
,
value
, and words
Example
function square(n) {
return n * n;
}
var wrapped = _([1, 2, 3]);
// Returns an unwrapped value.
wrapped.reduce(_.add);
// => 6
// Returns a wrapped value.
var squares = wrapped.map(square);
_.isArray(squares);
// => false
_.isArray(squares.value());
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to wrap in a |
Returns:
Returns the new lodash
wrapper instance.
- Type
- Object
Members
(static) assign
- Source:
Assigns own enumerable properties of source objects to the destination object. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
Note: This method mutates object
and is loosely based on
Object.assign
.
Example
function Foo() {
this.c = 3;
}
function Bar() {
this.e = 5;
}
Foo.prototype.d = 4;
Bar.prototype.f = 6;
_.assign({ 'a': 1 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3, 'e': 5 }
(static) assignWith
- Source:
This method is like _.assign
except that it accepts customizer
which
is invoked to produce the assigned values. If customizer
returns undefined
assignment is handled by the method instead. The customizer
is invoked
with five arguments: (objValue, srcValue, key, object, source).
Note: This method mutates object
.
Example
function customizer(objValue, srcValue) {
return _.isUndefined(objValue) ? srcValue : objValue;
}
var defaults = _.partialRight(_.assignWith, customizer);
defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
// => { 'a': 1, 'b': 2 }
(static) at
This method is the wrapper version of _.at
.
Example
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
_(object).at(['a[0].b.c', 'a[1]']).value();
// => [3, 4]
_(['a', 'b', 'c']).at(0, 2).value();
// => ['a', 'c']
(static) at
- Source:
Creates an array of values corresponding to paths
of object
.
Example
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
_.at(object, ['a[0].b.c', 'a[1]']);
// => [3, 4]
_.at(['a', 'b', 'c'], 0, 2);
// => ['a', 'c']
(static) attempt
- Source:
Attempts to invoke func
, returning either the result or the caught error
object. Any additional arguments are provided to func
when it's invoked.
Example
// Avoid throwing errors for invalid selectors.
var elements = _.attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (_.isError(elements)) {
elements = [];
}
(static) bind
Creates a function that invokes func
with the this
binding of thisArg
and prepends any additional _.bind
arguments to those provided to the
bound function.
The _.bind.placeholder
value, which defaults to _
in monolithic builds,
may be used as a placeholder for partially applied arguments.
Note: Unlike native Function#bind
this method doesn't set the "length"
property of bound functions.
Example
var greet = function(greeting, punctuation) {
return greeting + ' ' + this.user + punctuation;
};
var object = { 'user': 'fred' };
var bound = _.bind(greet, object, 'hi');
bound('!');
// => 'hi fred!'
// Bound with placeholders.
var bound = _.bind(greet, object, _, '!');
bound('hi');
// => 'hi fred!'
(static) bindAll
- Source:
Binds methods of an object to the object itself, overwriting the existing method.
Note: This method doesn't set the "length" property of bound functions.
Example
var view = {
'label': 'docs',
'onClick': function() {
console.log('clicked ' + this.label);
}
};
_.bindAll(view, 'onClick');
jQuery(element).on('click', view.onClick);
// => logs 'clicked docs' when clicked
(static) bindKey
Creates a function that invokes the method at object[key]
and prepends
any additional _.bindKey
arguments to those provided to the bound function.
This method differs from _.bind
by allowing bound functions to reference
methods that may be redefined or don't yet exist.
See Peter Michaux's article
for more details.
The _.bindKey.placeholder
value, which defaults to _
in monolithic
builds, may be used as a placeholder for partially applied arguments.
Example
var object = {
'user': 'fred',
'greet': function(greeting, punctuation) {
return greeting + ' ' + this.user + punctuation;
}
};
var bound = _.bindKey(object, 'greet', 'hi');
bound('!');
// => 'hi fred!'
object.greet = function(greeting, punctuation) {
return greeting + 'ya ' + this.user + punctuation;
};
bound('!');
// => 'hiya fred!'
// Bound with placeholders.
var bound = _.bindKey(object, 'greet', _, '!');
bound('hi');
// => 'hiya fred!'
(static) camelCase
- Source:
Converts string
to camel case.
Example
_.camelCase('Foo Bar');
// => 'fooBar'
_.camelCase('--foo-bar');
// => 'fooBar'
_.camelCase('__foo_bar__');
// => 'fooBar'
(static) ceil
- Source:
Computes number
rounded up to precision
.
Example
_.ceil(4.006);
// => 5
_.ceil(6.004, 2);
// => 6.01
_.ceil(6040, -2);
// => 6100
(static) chain
Enables explicit method chaining on the wrapper object.
Example
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
// A sequence without explicit chaining.
_(users).head();
// => { 'user': 'barney', 'age': 36 }
// A sequence with explicit chaining.
_(users)
.chain()
.head()
.pick('user')
.value();
// => { 'user': 'barney' }
(static) commit
Executes the chained sequence and returns the wrapped result.
Example
var array = [1, 2];
var wrapped = _(array).push(3);
console.log(array);
// => [1, 2]
wrapped = wrapped.commit();
console.log(array);
// => [1, 2, 3]
wrapped.last();
// => 3
console.log(array);
// => [1, 2, 3]
(static) concat
Creates a new array concatenating array
with any additional arrays
and/or values.
Example
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// => [1, 2, 3, [4]]
console.log(array);
// => [1]
(static) countBy
Creates an object composed of keys generated from the results of running
each element of collection
through iteratee
. The corresponding value
of each key is the number of times the key was returned by iteratee
.
The iteratee is invoked with one argument: (value).
Example
_.countBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': 1, '6': 2 }
_.countBy(['one', 'two', 'three'], 'length');
// => { '3': 2, '5': 1 }
(static) defaults
- Source:
Assigns own and inherited enumerable properties of source objects to the
destination object for all destination properties that resolve to undefined
.
Source objects are applied from left to right. Once a property is set,
additional values of the same property are ignored.
Note: This method mutates object
.
Example
_.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
// => { 'user': 'barney', 'age': 36 }
(static) defaultsDeep
- Source:
This method is like _.defaults
except that it recursively assigns
default properties.
Note: This method mutates object
.
Example
_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
// => { 'user': { 'name': 'barney', 'age': 36 } }
(static) defer
Defers invoking the func
until the current call stack has cleared. Any
additional arguments are provided to func
when it's invoked.
Example
_.defer(function(text) {
console.log(text);
}, 'deferred');
// => logs 'deferred' after one or more milliseconds
(static) delay
Invokes func
after wait
milliseconds. Any additional arguments are
provided to func
when it's invoked.
Example
_.delay(function(text) {
console.log(text);
}, 1000, 'later');
// => logs 'later' after one second
(static) difference
Creates an array of unique array
values not included in the other
given arrays using SameValueZero
for equality comparisons.
Example
_.difference([3, 2, 1], [4, 2]);
// => [3, 1]
(static) differenceBy
This method is like _.difference
except that it accepts iteratee
which
is invoked for each element of array
and values
to generate the criterion
by which uniqueness is computed. The iteratee is invoked with one argument: (value).
Example
_.differenceBy([3.1, 2.2, 1.3], [4.4, 2.5], Math.floor);
// => [3.1, 1.3]
// The `_.property` iteratee shorthand.
_.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
// => [{ 'x': 2 }]
(static) differenceWith
This method is like _.difference
except that it accepts comparator
which is invoked to compare elements of array
to values
. The comparator
is invoked with two arguments: (arrVal, othVal).
Example
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
_.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
// => [{ 'x': 2, 'y': 1 }]
(static) extend
- Source:
This method is like _.assign
except that it iterates over own and
inherited source properties.
Note: This method mutates object
.
Example
function Foo() {
this.b = 2;
}
function Bar() {
this.d = 4;
}
Foo.prototype.c = 3;
Bar.prototype.e = 5;
_.assignIn({ 'a': 1 }, new Foo, new Bar);
// => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
(static) extendWith
- Source:
This method is like _.assignIn
except that it accepts customizer
which
is invoked to produce the assigned values. If customizer
returns undefined
assignment is handled by the method instead. The customizer
is invoked
with five arguments: (objValue, srcValue, key, object, source).
Note: This method mutates object
.
Example
function customizer(objValue, srcValue) {
return _.isUndefined(objValue) ? srcValue : objValue;
}
var defaults = _.partialRight(_.assignInWith, customizer);
defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
// => { 'a': 1, 'b': 2 }
(static) flatMap
This method is the wrapper version of _.flatMap
.
Example
function duplicate(n) {
return [n, n];
}
_([1, 2]).flatMap(duplicate).value();
// => [1, 1, 2, 2]
(static) floor
- Source:
Computes number
rounded down to precision
.
Example
_.floor(4.006);
// => 4
_.floor(0.046, 2);
// => 0.04
_.floor(4060, -2);
// => 4000
(static) flow
- Source:
Creates a function that returns the result of invoking the given functions
with the this
binding of the created function, where each successive
invocation is supplied the return value of the previous.
Example
function square(n) {
return n * n;
}
var addSquare = _.flow(_.add, square);
addSquare(1, 2);
// => 9
(static) flowRight
- Source:
This method is like _.flow
except that it creates a function that
invokes the given functions from right to left.
Example
function square(n) {
return n * n;
}
var addSquare = _.flowRight(square, _.add);
addSquare(1, 2);
// => 9
(static) groupBy
Creates an object composed of keys generated from the results of running
each element of collection
through iteratee
. The corresponding value
of each key is an array of elements responsible for generating the key.
The iteratee is invoked with one argument: (value).
Example
_.groupBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': [4.2], '6': [6.1, 6.3] }
// The `_.property` iteratee shorthand.
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }
(static) intersection
Creates an array of unique values that are included in all given arrays
using SameValueZero
for equality comparisons.
Example
_.intersection([2, 1], [4, 2], [1, 2]);
// => [2]
(static) intersectionBy
This method is like _.intersection
except that it accepts iteratee
which is invoked for each element of each arrays
to generate the criterion
by which uniqueness is computed. The iteratee is invoked with one argument: (value).
Example
_.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
// => [2.1]
// The `_.property` iteratee shorthand.
_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }]
(static) intersectionWith
This method is like _.intersection
except that it accepts comparator
which is invoked to compare elements of arrays
. The comparator is invoked
with two arguments: (arrVal, othVal).
Example
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.intersectionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }]
(static) invert
- Source:
Creates an object composed of the inverted keys and values of object
.
If object
contains duplicate values, subsequent values overwrite property
assignments of previous values.
Example
var object = { 'a': 1, 'b': 2, 'c': 1 };
_.invert(object);
// => { '1': 'c', '2': 'b' }
(static) invertBy
- Source:
This method is like _.invert
except that the inverted object is generated
from the results of running each element of object
through iteratee
.
The corresponding inverted value of each inverted key is an array of keys
responsible for generating the inverted value. The iteratee is invoked
with one argument: (value).
Example
var object = { 'a': 1, 'b': 2, 'c': 1 };
_.invertBy(object);
// => { '1': ['a', 'c'], '2': ['b'] }
_.invertBy(object, function(value) {
return 'group' + value;
});
// => { 'group1': ['a', 'c'], 'group2': ['b'] }
(static) invoke
- Source:
Invokes the method at path
of object
.
Example
var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
_.invoke(object, 'a[0].b.c.slice', 1, 3);
// => [2, 3]
(static) invokeMap
Invokes the method at path
of each element in collection
, returning
an array of the results of each invoked method. Any additional arguments
are provided to each invoked method. If methodName
is a function it's
invoked for, and this
bound to, each element in collection
.
Example
_.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
// => [[1, 5, 7], [1, 2, 3]]
_.invokeMap([123, 456], String.prototype.split, '');
// => [['1', '2', '3'], ['4', '5', '6']]
(static) isArray :function
Checks if value
is classified as an Array
object.
Type:
- function
Example
_.isArray([1, 2, 3]);
// => true
_.isArray(document.body.children);
// => false
_.isArray('abc');
// => false
_.isArray(_.noop);
// => false
(static) isBuffer
Checks if value
is a buffer.
Example
_.isBuffer(new Buffer(2));
// => true
_.isBuffer(new Uint8Array(2));
// => false
(static) kebabCase
- Source:
Converts string
to kebab case.
Example
_.kebabCase('Foo Bar');
// => 'foo-bar'
_.kebabCase('fooBar');
// => 'foo-bar'
_.kebabCase('__foo_bar__');
// => 'foo-bar'
(static) keyBy
Creates an object composed of keys generated from the results of running
each element of collection
through iteratee
. The corresponding value
of each key is the last element responsible for generating the key. The
iteratee is invoked with one argument: (value).
Example
var array = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
_.keyBy(array, function(o) {
return String.fromCharCode(o.code);
});
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
_.keyBy(array, 'dir');
// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
(static) lowerCase
- Source:
Converts string
, as space separated words, to lower case.
Example
_.lowerCase('--Foo-Bar');
// => 'foo bar'
_.lowerCase('fooBar');
// => 'foo bar'
_.lowerCase('__FOO_BAR__');
// => 'foo bar'
(static) lowerFirst
- Source:
Converts the first character of string
to lower case.
Example
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'
(static) merge
- Source:
Recursively merges own and inherited enumerable properties of source objects
into the destination object. Source properties that resolve to undefined
are skipped if a destination value exists. Array and plain object properties
are merged recursively. Other objects and value types are overridden by
assignment. Source objects are applied from left to right. Subsequent
sources overwrite property assignments of previous sources.
Note: This method mutates object
.
Example
var users = {
'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
};
var ages = {
'data': [{ 'age': 36 }, { 'age': 40 }]
};
_.merge(users, ages);
// => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
(static) mergeWith
- Source:
This method is like _.merge
except that it accepts customizer
which
is invoked to produce the merged values of the destination and source
properties. If customizer
returns undefined
merging is handled by the
method instead. The customizer
is invoked with seven arguments:
(objValue, srcValue, key, object, source, stack).
Note: This method mutates object
.
Example
function customizer(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
}
var object = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var other = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.mergeWith(object, other, customizer);
// => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
(static) method
- Source:
Creates a function that invokes the method at path
of a given object.
Any additional arguments are provided to the invoked method.
Example
var objects = [
{ 'a': { 'b': { 'c': _.constant(2) } } },
{ 'a': { 'b': { 'c': _.constant(1) } } }
];
_.map(objects, _.method('a.b.c'));
// => [2, 1]
_.invokeMap(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
// => [1, 2]
(static) methodOf
- Source:
The opposite of _.method
; this method creates a function that invokes
the method at a given path of object
. Any additional arguments are
provided to the invoked method.
Example
var array = _.times(3, _.constant),
object = { 'a': array, 'b': array, 'c': array };
_.map(['a[2]', 'c[0]'], _.methodOf(object));
// => [2, 0]
_.map([['a', '2'], ['c', '0']], _.methodOf(object));
// => [2, 0]
(static) next
Gets the next value on a wrapped object following the iterator protocol.
Example
var wrapped = _([1, 2]);
wrapped.next();
// => { 'done': false, 'value': 1 }
wrapped.next();
// => { 'done': false, 'value': 2 }
wrapped.next();
// => { 'done': true, 'value': undefined }
(static) now :function
Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).
Type:
- function
Example
_.defer(function(stamp) {
console.log(_.now() - stamp);
}, _.now());
// => logs the number of milliseconds it took for the deferred function to be invoked
(static) omit
- Source:
The opposite of _.pick
; this method creates an object composed of the
own and inherited enumerable properties of object
that are not omitted.
Example
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.omit(object, ['a', 'c']);
// => { 'b': '2' }
(static) over
- Source:
Creates a function that invokes iteratees
with the arguments provided
to the created function and returns their results.
Example
var func = _.over(Math.max, Math.min);
func(1, 2, 3, 4);
// => [4, 1]
(static) overArgs
Creates a function that invokes func
with arguments transformed by
corresponding transforms
.
Example
function doubled(n) {
return n * 2;
}
function square(n) {
return n * n;
}
var func = _.overArgs(function(x, y) {
return [x, y];
}, square, doubled);
func(9, 3);
// => [81, 6]
func(10, 5);
// => [100, 10]
(static) overEvery
- Source:
Creates a function that checks if all of the predicates
return
truthy when invoked with the arguments provided to the created function.
Example
var func = _.overEvery(Boolean, isFinite);
func('1');
// => true
func(null);
// => false
func(NaN);
// => false
(static) overSome
- Source:
Creates a function that checks if any of the predicates
return
truthy when invoked with the arguments provided to the created function.
Example
var func = _.overSome(Boolean, isFinite);
func('1');
// => true
func(null);
// => true
func(NaN);
// => false
(static) partial
Creates a function that invokes func
with partial
arguments prepended
to those provided to the new function. This method is like _.bind
except
it does not alter the this
binding.
The _.partial.placeholder
value, which defaults to _
in monolithic
builds, may be used as a placeholder for partially applied arguments.
Note: This method doesn't set the "length" property of partially applied functions.
Example
var greet = function(greeting, name) {
return greeting + ' ' + name;
};
var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// => 'hello fred'
// Partially applied with placeholders.
var greetFred = _.partial(greet, _, 'fred');
greetFred('hi');
// => 'hi fred'
(static) partialRight
This method is like _.partial
except that partially applied arguments
are appended to those provided to the new function.
The _.partialRight.placeholder
value, which defaults to _
in monolithic
builds, may be used as a placeholder for partially applied arguments.
Note: This method doesn't set the "length" property of partially applied functions.
Example
var greet = function(greeting, name) {
return greeting + ' ' + name;
};
var greetFred = _.partialRight(greet, 'fred');
greetFred('hi');
// => 'hi fred'
// Partially applied with placeholders.
var sayHelloTo = _.partialRight(greet, 'hello', _);
sayHelloTo('fred');
// => 'hello fred'
(static) partition
Creates an array of elements split into two groups, the first of which
contains elements predicate
returns truthy for, the second of which
contains elements predicate
returns falsey for. The predicate is
invoked with one argument: (value).
Example
var users = [
{ 'user': 'barney', 'age': 36, 'active': false },
{ 'user': 'fred', 'age': 40, 'active': true },
{ 'user': 'pebbles', 'age': 1, 'active': false }
];
_.partition(users, function(o) { return o.active; });
// => objects for [['fred'], ['barney', 'pebbles']]
// The `_.matches` iteratee shorthand.
_.partition(users, { 'age': 1, 'active': false });
// => objects for [['pebbles'], ['barney', 'fred']]
// The `_.matchesProperty` iteratee shorthand.
_.partition(users, ['active', false]);
// => objects for [['barney', 'pebbles'], ['fred']]
// The `_.property` iteratee shorthand.
_.partition(users, 'active');
// => objects for [['fred'], ['barney', 'pebbles']]
(static) pick
- Source:
Creates an object composed of the picked object
properties.
Example
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }
(static) plant
Creates a clone of the chained sequence planting value
as the wrapped value.
Example
function square(n) {
return n * n;
}
var wrapped = _([1, 2]).map(square);
var other = wrapped.plant([3, 4]);
other.value();
// => [9, 16]
wrapped.value();
// => [1, 4]
(static) pull
Removes all given values from array
using
SameValueZero
for equality comparisons.
Note: Unlike _.without
, this method mutates array
. Use _.remove
to remove elements from an array by predicate.
Example
var array = [1, 2, 3, 1, 2, 3];
_.pull(array, 2, 3);
console.log(array);
// => [1, 1]
(static) pullAt
Removes elements from array
corresponding to indexes
and returns an
array of removed elements.
Note: Unlike _.at
, this method mutates array
.
Example
var array = [5, 10, 15, 20];
var evens = _.pullAt(array, 1, 3);
console.log(array);
// => [5, 15]
console.log(evens);
// => [10, 20]
(static) range
- Source:
Creates an array of numbers (positive and/or negative) progressing from
start
up to, but not including, end
. A step of -1
is used if a negative
start
is specified without an end
or step
. If end
is not specified
it's set to start
with start
then set to 0
.
Note: JavaScript follows the IEEE-754 standard for resolving floating-point values which can produce unexpected results.
Example
_.range(4);
// => [0, 1, 2, 3]
_.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);
// => []
(static) rangeRight
- Source:
This method is like _.range
except that it populates values in
descending order.
Example
_.rangeRight(4);
// => [3, 2, 1, 0]
_.rangeRight(-4);
// => [-3, -2, -1, 0]
_.rangeRight(1, 5);
// => [4, 3, 2, 1]
_.rangeRight(0, 20, 5);
// => [15, 10, 5, 0]
_.rangeRight(0, -4, -1);
// => [-3, -2, -1, 0]
_.rangeRight(1, 4, 0);
// => [1, 1, 1]
_.rangeRight(0);
// => []
(static) rearg
Creates a function that invokes func
with arguments arranged according
to the specified indexes where the argument value at the first index is
provided as the first argument, the argument value at the second index is
provided as the second argument, and so on.
Example
var rearged = _.rearg(function(a, b, c) {
return [a, b, c];
}, 2, 0, 1);
rearged('b', 'c', 'a')
// => ['a', 'b', 'c']
(static) reverse
This method is the wrapper version of _.reverse
.
Note: This method mutates the wrapped array.
Example
var array = [1, 2, 3];
_(array).reverse().value()
// => [3, 2, 1]
console.log(array);
// => [3, 2, 1]
(static) round
- Source:
Computes number
rounded to precision
.
Example
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
(static) snakeCase
- Source:
Converts string
to snake case.
Example
_.snakeCase('Foo Bar');
// => 'foo_bar'
_.snakeCase('fooBar');
// => 'foo_bar'
_.snakeCase('--foo-bar');
// => 'foo_bar'
(static) sortBy
Creates an array of elements, sorted in ascending order by the results of running each element in a collection through each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).
Example
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 42 },
{ 'user': 'barney', 'age': 34 }
];
_.sortBy(users, function(o) { return o.user; });
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
_.sortBy(users, 'user', function(o) {
return Math.floor(o.age / 10);
});
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
(static) startCase
- Source:
Converts string
to start case.
Example
_.startCase('--foo-bar');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__foo_bar__');
// => 'Foo Bar'
(static) union
Creates an array of unique values, in order, from all given arrays using
SameValueZero
for equality comparisons.
Example
_.union([2, 1], [4, 2], [1, 2]);
// => [2, 1, 4]
(static) unionBy
This method is like _.union
except that it accepts iteratee
which is
invoked for each element of each arrays
to generate the criterion by which
uniqueness is computed. The iteratee is invoked with one argument: (value).
Example
_.unionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
// => [2.1, 1.2, 4.3]
// The `_.property` iteratee shorthand.
_.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]
(static) unionWith
This method is like _.union
except that it accepts comparator
which
is invoked to compare elements of arrays
. The comparator is invoked
with two arguments: (arrVal, othVal).
Example
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.unionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
(static) upperCase
- Source:
Converts string
, as space separated words, to upper case.
Example
_.upperCase('--foo-bar');
// => 'FOO BAR'
_.upperCase('fooBar');
// => 'FOO BAR'
_.upperCase('__foo_bar__');
// => 'FOO BAR'
(static) upperFirst
- Source:
Converts the first character of string
to upper case.
Example
_.upperFirst('fred');
// => 'Fred'
_.upperFirst('FRED');
// => 'FRED'
(static) value
Executes the chained sequence to extract the unwrapped value.
Example
_([1, 2, 3]).value();
// => [1, 2, 3]
(static) without
Creates an array excluding all given values using
SameValueZero
for equality comparisons.
Example
_.without([1, 2, 1, 3], 1, 2);
// => [3]
(static) xor
Creates an array of unique values that is the symmetric difference of the given arrays.
Example
_.xor([2, 1], [4, 2]);
// => [1, 4]
(static) xorBy
This method is like _.xor
except that it accepts iteratee
which is
invoked for each element of each arrays
to generate the criterion by which
uniqueness is computed. The iteratee is invoked with one argument: (value).
Example
_.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor);
// => [1.2, 4.3]
// The `_.property` iteratee shorthand.
_.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 2 }]
(static) xorWith
This method is like _.xor
except that it accepts comparator
which is
invoked to compare elements of arrays
. The comparator is invoked with
two arguments: (arrVal, othVal).
Example
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.xorWith(objects, others, _.isEqual);
// => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
(static) zip
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(['fred', 'barney'], [30, 40], [true, false]);
// => [['fred', 30, true], ['barney', 40, false]]
(static) zipWith
This method is like _.zip
except that it accepts iteratee
to specify
how grouped values should be combined. The iteratee is invoked with the
elements of each group: (...group).
Example
_.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
return a + b + c;
});
// => [111, 222]
Methods
(static) add(augend, addend) → {number}
- Source:
Adds two numbers.
Example
_.add(6, 4);
// => 10
Parameters:
Name | Type | Description |
---|---|---|
augend |
number | The first number in an addition. |
addend |
number | The second number in an addition. |
Returns:
Returns the total.
- Type
- number
(static) after(n, func) → {function}
The opposite of _.before
; this method creates a function that invokes
func
once it's called n
or more 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 the two async saves have completed
Parameters:
Name | Type | Description |
---|---|---|
n |
number | The number of calls before |
func |
function | The function to restrict. |
Returns:
Returns the new restricted function.
- Type
- function
(static) ary(func, nopt) → {function}
Creates a function that accepts up to n
arguments, ignoring any
additional arguments.
Example
_.map(['6', '8', '10'], _.ary(parseInt, 1));
// => [6, 8, 10]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
function | The function to cap arguments for. |
||
n |
number |
<optional> |
func.length | The arity cap. |
Returns:
Returns the new function.
- Type
- function
(static) before(n, func) → {function}
Creates a function that invokes func
, with the this
binding and arguments
of the created function, while it's called less than n
times. Subsequent
calls to the created function return the result of the last func
invocation.
Example
jQuery(element).on('click', _.before(5, addContactToList));
// => allows adding up to 4 contacts to the list
Parameters:
Name | Type | Description |
---|---|---|
n |
number | The number of calls at which |
func |
function | The function to restrict. |
Returns:
Returns the new restricted function.
- Type
- function
(static) capitalize(stringopt) → {string}
- Source:
Converts the first character of string
to upper case and the remaining
to lower case.
Example
_.capitalize('FRED');
// => 'Fred'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to capitalize. |
Returns:
Returns the capitalized string.
- Type
- string
(static) castArray(value) → {Array}
Casts value
as an array if it's not one.
Example
_.castArray(1);
// => [1]
_.castArray({ 'a': 1 });
// => [{ 'a': 1 }]
_.castArray('abc');
// => ['abc']
_.castArray(null);
// => [null]
_.castArray(undefined);
// => [undefined]
_.castArray();
// => []
var array = [1, 2, 3];
console.log(_.castArray(array) === array);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to inspect. |
Returns:
Returns the cast array.
- Type
- Array
(static) chain(value) → {Object}
Creates a lodash
object that wraps value
with explicit method chaining enabled.
The result of such method chaining must be unwrapped with _#value
.
Example
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'pebbles', 'age': 1 }
];
var youngest = _
.chain(users)
.sortBy('age')
.map(function(o) {
return o.user + ' is ' + o.age;
})
.head()
.value();
// => 'pebbles is 1'
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to wrap. |
Returns:
Returns the new lodash
wrapper instance.
- Type
- Object
(static) chunk(array, sizeopt) → {Array}
Creates an array of elements split into groups the length of size
.
If array
can't be split evenly, the final chunk will be the remaining
elements.
Example
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to process. |
||
size |
number |
<optional> |
0 | The length of each chunk. |
Returns:
Returns the new array containing chunks.
- Type
- Array
(static) clamp(number, loweropt, upper) → {number}
- Source:
Clamps number
within the inclusive lower
and upper
bounds.
Example
_.clamp(-10, -5, 5);
// => -5
_.clamp(10, -5, 5);
// => 5
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
number |
number | The number to clamp. |
|
lower |
number |
<optional> |
The lower bound. |
upper |
number | The upper bound. |
Returns:
Returns the clamped number.
- Type
- number
(static) clone(value) → {*}
Creates a shallow clone of value
.
Note: This method is loosely based on the
structured clone algorithm
and supports cloning arrays, array buffers, booleans, date objects, maps,
numbers, Object
objects, regexes, sets, strings, symbols, and typed
arrays. The own enumerable properties of arguments
objects are cloned
as plain objects. An empty object is returned for uncloneable values such
as error objects, functions, DOM nodes, and WeakMaps.
Example
var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to clone. |
Returns:
Returns the cloned value.
- Type
- *
(static) cloneDeep(value) → {*}
This method is like _.clone
except that it recursively clones value
.
Example
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to recursively clone. |
Returns:
Returns the deep cloned value.
- Type
- *
(static) cloneDeepWith(value, customizeropt) → {*}
This method is like _.cloneWith
except that it recursively clones value
.
Example
function customizer(value) {
if (_.isElement(value)) {
return value.cloneNode(true);
}
}
var el = _.cloneDeepWith(document.body, customizer);
console.log(el === document.body);
// => false
console.log(el.nodeName);
// => 'BODY'
console.log(el.childNodes.length);
// => 20
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
value |
* | The value to recursively clone. |
|
customizer |
function |
<optional> |
The function to customize cloning. |
Returns:
Returns the deep cloned value.
- Type
- *
(static) cloneWith(value, customizeropt) → {*}
This method is like _.clone
except that it accepts customizer
which
is invoked to produce the cloned value. If customizer
returns undefined
cloning is handled by the method instead. The customizer
is invoked with
up to four arguments; (value [, index|key, object, stack]).
Example
function customizer(value) {
if (_.isElement(value)) {
return value.cloneNode(false);
}
}
var el = _.cloneWith(document.body, customizer);
console.log(el === document.body);
// => false
console.log(el.nodeName);
// => 'BODY'
console.log(el.childNodes.length);
// => 0
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
value |
* | The value to clone. |
|
customizer |
function |
<optional> |
The function to customize cloning. |
Returns:
Returns the cloned value.
- Type
- *
(static) compact(array) → {Array}
Creates an array with all falsey values removed. The values false
, null
,
0
, ""
, undefined
, and NaN
are falsey.
Example
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to compact. |
Returns:
Returns the new array of filtered values.
- Type
- Array
(static) cond(pairs) → {function}
- Source:
Creates a function that iterates over pairs
invoking the corresponding
function of the first predicate to return truthy. The predicate-function
pairs are invoked with the this
binding and arguments of the created
function.
Example
var func = _.cond([
[_.matches({ 'a': 1 }), _.constant('matches A')],
[_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
[_.constant(true), _.constant('no match')]
]);
func({ 'a': 1, 'b': 2 });
// => 'matches A'
func({ 'a': 0, 'b': 1 });
// => 'matches B'
func({ 'a': '1', 'b': '2' });
// => 'no match'
Parameters:
Name | Type | Description |
---|---|---|
pairs |
Array | The predicate-function pairs. |
Returns:
Returns the new function.
- Type
- function
(static) conforms(source) → {function}
- Source:
Creates a function that invokes the predicate properties of source
with
the corresponding property values of a given object, returning true
if
all predicates return truthy, else false
.
Example
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
_.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));
// => [{ 'user': 'fred', 'age': 40 }]
Parameters:
Name | Type | Description |
---|---|---|
source |
Object | The object of property predicates to conform to. |
Returns:
Returns the new function.
- Type
- function
(static) constant(value) → {function}
- Source:
Creates a function that returns value
.
Example
var object = { 'user': 'fred' };
var getter = _.constant(object);
getter() === object;
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to return from the new function. |
Returns:
Returns the new function.
- Type
- function
(static) create(prototype, propertiesopt) → {Object}
- Source:
Creates an object that inherits from the prototype
object. If a properties
object is given its own enumerable properties are assigned to the created object.
Example
function Shape() {
this.x = 0;
this.y = 0;
}
function Circle() {
Shape.call(this);
}
Circle.prototype = _.create(Shape.prototype, {
'constructor': Circle
});
var circle = new Circle;
circle instanceof Circle;
// => true
circle instanceof Shape;
// => true
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
prototype |
Object | The object to inherit from. |
|
properties |
Object |
<optional> |
The properties to assign to the object. |
Returns:
Returns the new object.
- Type
- Object
(static) curry(func, arityopt) → {function}
Creates a function that accepts arguments of func
and either invokes
func
returning its result, if at least arity
number of arguments have
been provided, or returns a function that accepts the remaining func
arguments, and so on. The arity of func
may be specified if func.length
is not sufficient.
The _.curry.placeholder
value, which defaults to _
in monolithic builds,
may be used as a placeholder for provided arguments.
Note: This method doesn't set the "length" property of curried functions.
Example
var abc = function(a, b, c) {
return [a, b, c];
};
var curried = _.curry(abc);
curried(1)(2)(3);
// => [1, 2, 3]
curried(1, 2)(3);
// => [1, 2, 3]
curried(1, 2, 3);
// => [1, 2, 3]
// Curried with placeholders.
curried(1)(_, 3)(2);
// => [1, 2, 3]
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) curryRight(func, arityopt) → {function}
This method is like _.curry
except that arguments are applied to func
in the manner of _.partialRight
instead of _.partial
.
The _.curryRight.placeholder
value, which defaults to _
in monolithic
builds, may be used as a placeholder for provided arguments.
Note: This method doesn't set the "length" property of curried functions.
Example
var abc = function(a, b, c) {
return [a, b, c];
};
var curried = _.curryRight(abc);
curried(3)(2)(1);
// => [1, 2, 3]
curried(2, 3)(1);
// => [1, 2, 3]
curried(1, 2, 3);
// => [1, 2, 3]
// Curried with placeholders.
curried(3)(1, _)(2);
// => [1, 2, 3]
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, waitopt, optionsopt) → {function}
Creates a debounced function that delays invoking func
until after wait
milliseconds have elapsed since the last time the debounced function was
invoked. The debounced function comes with a cancel
method to cancel
delayed func
invocations and a flush
method to immediately invoke them.
Provide an options object to indicate whether func
should be invoked on
the leading and/or trailing edge of the wait
timeout. The func
is invoked
with the last arguments provided to the debounced function. Subsequent calls
to the debounced function return the result of the last func
invocation.
Note: If leading
and trailing
options are true
, func
is invoked
on the trailing edge of the timeout only if the debounced function is
invoked more than once during the wait
timeout.
See David Corbacho's article
for details over the differences between _.debounce
and _.throttle
.
Example
// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
// Invoke `sendMail` when clicked, debouncing subsequent calls.
jQuery(element).on('click', _.debounce(sendMail, 300, {
'leading': true,
'trailing': false
}));
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// Cancel the trailing debounced invocation.
jQuery(window).on('popstate', debounced.cancel);
Parameters:
Name | Type | Attributes | Default | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
func |
function | The function to debounce. |
||||||||||||||||||||||
wait |
number |
<optional> |
0 | The number of milliseconds to delay. |
||||||||||||||||||||
options |
Object |
<optional> |
The options object. Properties
|
Returns:
Returns the new debounced function.
- Type
- function
(static) deburr(stringopt) → {string}
- Source:
Deburrs string
by converting latin-1 supplementary letters#Character_table)
to basic latin letters and removing combining diacritical marks.
Example
_.deburr('déjà vu');
// => 'deja vu'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to deburr. |
Returns:
Returns the deburred string.
- Type
- string
(static) drop(array, nopt) → {Array}
Creates a slice of array
with n
elements dropped from the beginning.
Example
_.drop([1, 2, 3]);
// => [2, 3]
_.drop([1, 2, 3], 2);
// => [3]
_.drop([1, 2, 3], 5);
// => []
_.drop([1, 2, 3], 0);
// => [1, 2, 3]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
n |
number |
<optional> |
1 | The number of elements to drop. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) dropRight(array, nopt) → {Array}
Creates a slice of array
with n
elements dropped from the end.
Example
_.dropRight([1, 2, 3]);
// => [1, 2]
_.dropRight([1, 2, 3], 2);
// => [1]
_.dropRight([1, 2, 3], 5);
// => []
_.dropRight([1, 2, 3], 0);
// => [1, 2, 3]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
n |
number |
<optional> |
1 | The number of elements to drop. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) dropRightWhile(array, predicateopt) → {Array}
Creates a slice of array
excluding elements dropped from the end.
Elements are dropped until predicate
returns falsey. The predicate is
invoked with three arguments: (value, index, array).
Example
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': false }
];
_.dropRightWhile(users, function(o) { return !o.active; });
// => objects for ['barney']
// The `_.matches` iteratee shorthand.
_.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
// => objects for ['barney', 'fred']
// The `_.matchesProperty` iteratee shorthand.
_.dropRightWhile(users, ['active', false]);
// => objects for ['barney']
// The `_.property` iteratee shorthand.
_.dropRightWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) dropWhile(array, predicateopt) → {Array}
Creates a slice of array
excluding elements dropped from the beginning.
Elements are dropped until predicate
returns falsey. The predicate is
invoked with three arguments: (value, index, array).
Example
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.dropWhile(users, function(o) { return !o.active; });
// => objects for ['pebbles']
// The `_.matches` iteratee shorthand.
_.dropWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['fred', 'pebbles']
// The `_.matchesProperty` iteratee shorthand.
_.dropWhile(users, ['active', false]);
// => objects for ['pebbles']
// The `_.property` iteratee shorthand.
_.dropWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) each(collection, iterateeopt) → {Array|Object}
Iterates over elements of collection
invoking iteratee
for each element.
The iteratee is invoked with three arguments: (value, index|key, collection).
Iteratee functions may exit iteration early by explicitly returning false
.
Note: As with other "Collections" methods, objects with a "length" property
are iterated like arrays. To avoid this behavior use _.forIn
or _.forOwn
for object iteration.
Example
_([1, 2]).forEach(function(value) {
console.log(value);
});
// => logs `1` then `2`
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
console.log(key);
});
// => logs 'a' then 'b' (iteration order is not guaranteed)
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns collection
.
- Type
- Array | Object
(static) eachRight(collection, iterateeopt) → {Array|Object}
This method is like _.forEach
except that it iterates over elements of
collection
from right to left.
Example
_.forEachRight([1, 2], function(value) {
console.log(value);
});
// => logs `2` then `1`
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns collection
.
- Type
- Array | Object
(static) endsWith(stringopt, targetopt, positionopt) → {boolean}
- Source:
Checks if string
ends with the given target string.
Example
_.endsWith('abc', 'c');
// => true
_.endsWith('abc', 'b');
// => false
_.endsWith('abc', 'b', 2);
// => true
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to search. |
target |
string |
<optional> |
The string to search for. |
|
position |
number |
<optional> |
string.length | The position to search from. |
Returns:
Returns true
if string
ends with target
, else false
.
- Type
- boolean
(static) eq(value, other) → {boolean}
Performs a SameValueZero
comparison between two values to determine if they are equivalent.
Example
var object = { 'user': 'fred' };
var other = { 'user': 'fred' };
_.eq(object, object);
// => true
_.eq(object, other);
// => false
_.eq('a', 'a');
// => true
_.eq('a', Object('a'));
// => false
_.eq(NaN, NaN);
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to compare. |
other |
* | The other value to compare. |
Returns:
Returns true
if the values are equivalent, else false
.
- Type
- boolean
(static) escape(stringopt) → {string}
- Source:
Converts the characters "&", "<", ">", '"', "'", and "`" in string
to
their corresponding HTML entities.
Note: No other characters are escaped. To escape additional characters use a third-party library like he.
Though the ">" character is escaped for symmetry, characters like ">" and "/" don't need escaping in HTML and have no special meaning unless they're part of a tag or unquoted attribute value. See Mathias Bynens's article (under "semi-related fun fact") for more details.
Backticks are escaped because in IE < 9, they can break out of attribute values or HTML comments. See #59, #102, #108, and #133 of the HTML5 Security Cheatsheet for more details.
When working with HTML you should always quote attribute values to reduce XSS vectors.
Example
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to escape. |
Returns:
Returns the escaped string.
- Type
- string
(static) escapeRegExp(stringopt) → {string}
- Source:
Escapes the RegExp
special characters "^", "$", "\", ".", "*", "+",
"?", "(", ")", "[", "]", "{", "}", and "|" in string
.
Example
_.escapeRegExp('[lodash](https://lodash.com/)');
// => '\[lodash\]\(https://lodash\.com/\)'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to escape. |
Returns:
Returns the escaped string.
- Type
- string
(static) every(collection, predicateopt) → {boolean}
Checks if predicate
returns truthy for all elements of collection
.
Iteration is stopped once predicate
returns falsey. The predicate is
invoked with three arguments: (value, index|key, collection).
Example
_.every([true, 1, null, 'yes'], Boolean);
// => false
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false }
];
// The `_.matches` iteratee shorthand.
_.every(users, { 'user': 'barney', 'active': false });
// => false
// The `_.matchesProperty` iteratee shorthand.
_.every(users, ['active', false]);
// => true
// The `_.property` iteratee shorthand.
_.every(users, 'active');
// => false
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns true
if all elements pass the predicate check, else false
.
- Type
- boolean
(static) fill(array, value, startopt, endopt) → {Array}
Fills elements of array
with value
from start
up to, but not
including, end
.
Note: This method mutates array
.
Example
var array = [1, 2, 3];
_.fill(array, 'a');
console.log(array);
// => ['a', 'a', 'a']
_.fill(Array(3), 2);
// => [2, 2, 2]
_.fill([4, 6, 8, 10], '*', 1, 3);
// => [4, '*', '*', 10]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to fill. |
||
value |
* | The value to fill |
||
start |
number |
<optional> |
0 | The start position. |
end |
number |
<optional> |
array.length | The end position. |
Returns:
Returns array
.
- Type
- Array
(static) filter(collection, predicateopt) → {Array}
Iterates over elements of collection
, returning an array of all elements
predicate
returns truthy for. The predicate is invoked with three arguments:
(value, index|key, collection).
Example
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the new filtered array.
- Type
- Array
(static) find(collection, predicateopt) → {*}
Iterates over elements of collection
, returning the first element
predicate
returns truthy for. The predicate is invoked with three arguments:
(value, index|key, collection).
Example
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
];
_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'
// The `_.matches` iteratee shorthand.
_.find(users, { 'age': 1, 'active': true });
// => object for 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.find(users, ['active', false]);
// => object for 'fred'
// The `_.property` iteratee shorthand.
_.find(users, 'active');
// => object for 'barney'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to search. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the matched element, else undefined
.
- Type
- *
(static) findIndex(array, predicateopt) → {number}
This method is like _.find
except that it returns the index of the first
element predicate
returns truthy for instead of the element itself.
Example
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0
// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1
// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0
// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to search. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the index of the found element, else -1
.
- Type
- number
(static) findKey(object, predicateopt) → {string|undefined}
- Source:
This method is like _.find
except that it returns the key of the first
element predicate
returns truthy for instead of the element itself.
Example
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)
// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// => 'fred'
// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// => 'barney'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to search. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the key of the matched element, else undefined
.
- Type
- string | undefined
(static) findLast(collection, predicateopt) → {*}
This method is like _.find
except that it iterates over elements of
collection
from right to left.
Example
_.findLast([1, 2, 3, 4], function(n) {
return n % 2 == 1;
});
// => 3
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to search. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the matched element, else undefined
.
- Type
- *
(static) findLastIndex(array, predicateopt) → {number}
This method is like _.findIndex
except that it iterates over elements
of collection
from right to left.
Example
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': false }
];
_.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
// => 2
// The `_.matches` iteratee shorthand.
_.findLastIndex(users, { 'user': 'barney', 'active': true });
// => 0
// The `_.matchesProperty` iteratee shorthand.
_.findLastIndex(users, ['active', false]);
// => 2
// The `_.property` iteratee shorthand.
_.findLastIndex(users, 'active');
// => 0
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to search. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the index of the found element, else -1
.
- Type
- number
(static) findLastKey(object, predicateopt) → {string|undefined}
- Source:
This method is like _.findKey
except that it iterates over elements of
a collection in the opposite order.
Example
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findLastKey(users, function(o) { return o.age < 40; });
// => returns 'pebbles' assuming `_.findKey` returns 'barney'
// The `_.matches` iteratee shorthand.
_.findLastKey(users, { 'age': 36, 'active': true });
// => 'barney'
// The `_.matchesProperty` iteratee shorthand.
_.findLastKey(users, ['active', false]);
// => 'fred'
// The `_.property` iteratee shorthand.
_.findLastKey(users, 'active');
// => 'pebbles'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to search. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the key of the matched element, else undefined
.
- Type
- string | undefined
(static) first(array) → {*}
Gets the first element of array
.
Example
_.head([1, 2, 3]);
// => 1
_.head([]);
// => undefined
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to query. |
Returns:
Returns the first element of array
.
- Type
- *
(static) flatMap(collection, iterateeopt) → {Array}
Creates an array of flattened values by running each element in collection
through iteratee
and concating its result to the other mapped values.
The iteratee is invoked with three arguments: (value, index|key, collection).
Example
function duplicate(n) {
return [n, n];
}
_.flatMap([1, 2], duplicate);
// => [1, 1, 2, 2]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the new flattened array.
- Type
- Array
(static) flatten(array) → {Array}
Flattens array
a single level deep.
Example
_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to flatten. |
Returns:
Returns the new flattened array.
- Type
- Array
(static) flattenDeep(array) → {Array}
Recursively flattens array
.
Example
_.flattenDeep([1, [2, [3, [4]], 5]]);
// => [1, 2, 3, 4, 5]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to flatten. |
Returns:
Returns the new flattened array.
- Type
- Array
(static) flattenDepth(array, depthopt) → {Array}
Recursively flatten array
up to depth
times.
Example
var array = [1, [2, [3, [4]], 5]];
_.flattenDepth(array, 1);
// => [1, 2, [3, [4]], 5]
_.flattenDepth(array, 2);
// => [1, 2, 3, [4], 5]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to flatten. |
||
depth |
number |
<optional> |
1 | The maximum recursion depth. |
Returns:
Returns the new flattened array.
- Type
- Array
(static) flip(func) → {function}
Creates a function that invokes func
with arguments reversed.
Example
var flipped = _.flip(function() {
return _.toArray(arguments);
});
flipped('a', 'b', 'c', 'd');
// => ['d', 'c', 'b', 'a']
Parameters:
Name | Type | Description |
---|---|---|
func |
function | The function to flip arguments for. |
Returns:
Returns the new function.
- Type
- function
(static) forIn(object, iterateeopt) → {Object}
- Source:
Iterates over own and inherited enumerable properties of an object invoking
iteratee
for each property. The iteratee is invoked with three arguments:
(value, key, object). Iteratee functions may exit iteration early by explicitly
returning false
.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forIn(new Foo, function(value, key) {
console.log(key);
});
// => logs 'a', 'b', then 'c' (iteration order is not guaranteed)
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns object
.
- Type
- Object
(static) forInRight(object, iterateeopt) → {Object}
- Source:
This method is like _.forIn
except that it iterates over properties of
object
in the opposite order.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forInRight(new Foo, function(value, key) {
console.log(key);
});
// => logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns object
.
- Type
- Object
(static) forOwn(object, iterateeopt) → {Object}
- Source:
Iterates over own enumerable properties of an object invoking iteratee
for each property. The iteratee is invoked with three arguments:
(value, key, object). Iteratee functions may exit iteration early by
explicitly returning false
.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forOwn(new Foo, function(value, key) {
console.log(key);
});
// => logs 'a' then 'b' (iteration order is not guaranteed)
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns object
.
- Type
- Object
(static) forOwnRight(object, iterateeopt) → {Object}
- Source:
This method is like _.forOwn
except that it iterates over properties of
object
in the opposite order.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forOwnRight(new Foo, function(value, key) {
console.log(key);
});
// => logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns object
.
- Type
- Object
(static) fromPairs(pairs) → {Object}
The inverse of _.toPairs
; this method returns an object composed
from key-value pairs
.
Example
_.fromPairs([['fred', 30], ['barney', 40]]);
// => { 'fred': 30, 'barney': 40 }
Parameters:
Name | Type | Description |
---|---|---|
pairs |
Array | The key-value pairs. |
Returns:
Returns the new object.
- Type
- Object
(static) functions(object) → {Array}
- Source:
Creates an array of function property names from own enumerable properties
of object
.
Example
function Foo() {
this.a = _.constant('a');
this.b = _.constant('b');
}
Foo.prototype.c = _.constant('c');
_.functions(new Foo);
// => ['a', 'b']
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to inspect. |
Returns:
Returns the new array of property names.
- Type
- Array
(static) functionsIn(object) → {Array}
- Source:
Creates an array of function property names from own and inherited
enumerable properties of object
.
Example
function Foo() {
this.a = _.constant('a');
this.b = _.constant('b');
}
Foo.prototype.c = _.constant('c');
_.functionsIn(new Foo);
// => ['a', 'b', 'c']
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to inspect. |
Returns:
Returns the new array of property names.
- Type
- Array
(static) get(object, path, defaultValueopt) → {*}
- Source:
Gets the value at path
of object
. If the resolved value is
undefined
the defaultValue
is used in its place.
Example
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
_.get(object, ['a', '0', 'b', 'c']);
// => 3
_.get(object, 'a.b.c', 'default');
// => 'default'
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The object to query. |
|
path |
Array | string | The path of the property to get. |
|
defaultValue |
* |
<optional> |
The value returned if the resolved value is |
Returns:
Returns the resolved value.
- Type
- *
(static) gt(value, other) → {boolean}
Checks if value
is greater than other
.
Example
_.gt(3, 1);
// => true
_.gt(3, 3);
// => false
_.gt(1, 3);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to compare. |
other |
* | The other value to compare. |
Returns:
Returns true
if value
is greater than other
, else false
.
- Type
- boolean
(static) gte(value, other) → {boolean}
Checks if value
is greater than or equal to other
.
Example
_.gte(3, 1);
// => true
_.gte(3, 3);
// => true
_.gte(1, 3);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to compare. |
other |
* | The other value to compare. |
Returns:
Returns true
if value
is greater than or equal to other
, else false
.
- Type
- boolean
(static) has(object, path) → {boolean}
- Source:
Checks if path
is a direct property of object
.
Example
var object = { 'a': { 'b': { 'c': 3 } } };
var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });
_.has(object, 'a');
// => true
_.has(object, 'a.b.c');
// => true
_.has(object, ['a', 'b', 'c']);
// => true
_.has(other, 'a');
// => false
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
path |
Array | string | The path to check. |
Returns:
Returns true
if path
exists, else false
.
- Type
- boolean
(static) hasIn(object, path) → {boolean}
- Source:
Checks if path
is a direct or inherited property of object
.
Example
var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });
_.hasIn(object, 'a');
// => true
_.hasIn(object, 'a.b.c');
// => true
_.hasIn(object, ['a', 'b', 'c']);
// => true
_.hasIn(object, 'b');
// => false
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
path |
Array | string | The path to check. |
Returns:
Returns true
if path
exists, else false
.
- Type
- boolean
(static) identity(value) → {*}
- Source:
This method returns the first argument given to it.
Example
var object = { 'user': 'fred' };
_.identity(object) === object;
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | Any value. |
Returns:
Returns value
.
- Type
- *
(static) includes(collection, value, fromIndexopt) → {boolean}
Checks if value
is in collection
. If collection
is a string it's checked
for a substring of value
, otherwise SameValueZero
is used for equality comparisons. If fromIndex
is negative, it's used as
the offset from the end of collection
.
Example
_.includes([1, 2, 3], 1);
// => true
_.includes([1, 2, 3], 1, 2);
// => false
_.includes({ 'user': 'fred', 'age': 40 }, 'fred');
// => true
_.includes('pebbles', 'eb');
// => true
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | string | The collection to search. |
||
value |
* | The value to search for. |
||
fromIndex |
number |
<optional> |
0 | The index to search from. |
Returns:
Returns true
if value
is found, else false
.
- Type
- boolean
(static) indexOf(array, value, fromIndexopt) → {number}
Gets the index at which the first occurrence of value
is found in array
using SameValueZero
for equality comparisons. If fromIndex
is negative, it's used as the offset
from the end of array
.
Example
_.indexOf([1, 2, 1, 2], 2);
// => 1
// Search from the `fromIndex`.
_.indexOf([1, 2, 1, 2], 2, 2);
// => 3
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to search. |
||
value |
* | The value to search for. |
||
fromIndex |
number |
<optional> |
0 | The index to search from. |
Returns:
Returns the index of the matched value, else -1
.
- Type
- number
(static) initial(array) → {Array}
Gets all but the last element of array
.
Example
_.initial([1, 2, 3]);
// => [1, 2]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to query. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) inRange(number, startopt, end) → {boolean}
- Source:
Checks if n
is between start
and up to but not including, end
. If
end
is not specified it's set to start
with start
then set to 0
.
If start
is greater than end
the params are swapped to support
negative ranges.
Example
_.inRange(3, 2, 4);
// => true
_.inRange(4, 8);
// => true
_.inRange(4, 2);
// => false
_.inRange(2, 2);
// => false
_.inRange(1.2, 2);
// => true
_.inRange(5.2, 4);
// => false
_.inRange(-3, -2, -6);
// => true
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
number |
number | The number to check. |
||
start |
number |
<optional> |
0 | The start of the range. |
end |
number | The end of the range. |
Returns:
Returns true
if number
is in the range, else false
.
- Type
- boolean
(static) isArguments(value) → {boolean}
Checks if value
is likely an arguments
object.
Example
_.isArguments(function() { return arguments; }());
// => true
_.isArguments([1, 2, 3]);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isArrayBuffer(value) → {boolean}
Checks if value
is classified as an ArrayBuffer
object.
Example
_.isArrayBuffer(new ArrayBuffer(2));
// => true
_.isArrayBuffer(new Array(2));
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isArrayLike(value) → {boolean}
Checks if value
is array-like. A value is considered array-like if it's
not a function and has a value.length
that's an integer greater than or
equal to 0
and less than or equal to Number.MAX_SAFE_INTEGER
.
Example
_.isArrayLike([1, 2, 3]);
// => true
_.isArrayLike(document.body.children);
// => true
_.isArrayLike('abc');
// => true
_.isArrayLike(_.noop);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is array-like, else false
.
- Type
- boolean
(static) isArrayLikeObject(value) → {boolean}
This method is like _.isArrayLike
except that it also checks if value
is an object.
Example
_.isArrayLikeObject([1, 2, 3]);
// => true
_.isArrayLikeObject(document.body.children);
// => true
_.isArrayLikeObject('abc');
// => false
_.isArrayLikeObject(_.noop);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is an array-like object, else false
.
- Type
- boolean
(static) isBoolean(value) → {boolean}
Checks if value
is classified as a boolean primitive or object.
Example
_.isBoolean(false);
// => true
_.isBoolean(null);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isDate(value) → {boolean}
Checks if value
is classified as a Date
object.
Example
_.isDate(new Date);
// => true
_.isDate('Mon April 23 2012');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isElement(value) → {boolean}
Checks if value
is likely a DOM element.
Example
_.isElement(document.body);
// => true
_.isElement('<body>');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is a DOM element, else false
.
- Type
- boolean
(static) isEmpty(value) → {boolean}
Checks if value
is empty. A value is considered empty unless it's an
arguments
object, array, string, or jQuery-like collection with a length
greater than 0
or an object with own enumerable properties.
Example
_.isEmpty(null);
// => true
_.isEmpty(true);
// => true
_.isEmpty(1);
// => true
_.isEmpty([1, 2, 3]);
// => false
_.isEmpty({ 'a': 1 });
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
Array | Object | string | The value to inspect. |
Returns:
Returns true
if value
is empty, else false
.
- Type
- boolean
(static) isEqual(value, other) → {boolean}
Performs a deep comparison between two values to determine if they are equivalent.
Note: This method supports comparing arrays, array buffers, booleans,
date objects, error objects, maps, numbers, Object
objects, regexes,
sets, strings, symbols, and typed arrays. Object
objects are compared
by their own, not inherited, enumerable properties. Functions and DOM
nodes are not supported.
Example
var object = { 'user': 'fred' };
var other = { 'user': 'fred' };
_.isEqual(object, other);
// => true
object === other;
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to compare. |
other |
* | The other value to compare. |
Returns:
Returns true
if the values are equivalent, else false
.
- Type
- boolean
(static) isEqualWith(value, other, customizeropt) → {boolean}
This method is like _.isEqual
except that it accepts customizer
which
is invoked to compare values. If customizer
returns undefined
comparisons
are handled by the method instead. The customizer
is invoked with up to
six arguments: (objValue, othValue [, index|key, object, other, stack]).
Example
function isGreeting(value) {
return /^h(?:i|ello)$/.test(value);
}
function customizer(objValue, othValue) {
if (isGreeting(objValue) && isGreeting(othValue)) {
return true;
}
}
var array = ['hello', 'goodbye'];
var other = ['hi', 'goodbye'];
_.isEqualWith(array, other, customizer);
// => true
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
value |
* | The value to compare. |
|
other |
* | The other value to compare. |
|
customizer |
function |
<optional> |
The function to customize comparisons. |
Returns:
Returns true
if the values are equivalent, else false
.
- Type
- boolean
(static) isError(value) → {boolean}
Checks if value
is an Error
, EvalError
, RangeError
, ReferenceError
,
SyntaxError
, TypeError
, or URIError
object.
Example
_.isError(new Error);
// => true
_.isError(Error);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is an error object, else false
.
- Type
- boolean
(static) isFinite(value) → {boolean}
Checks if value
is a finite primitive number.
Note: This method is based on Number.isFinite
.
Example
_.isFinite(3);
// => true
_.isFinite(Number.MAX_VALUE);
// => true
_.isFinite(3.14);
// => true
_.isFinite(Infinity);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is a finite number, else false
.
- Type
- boolean
(static) isFunction(value) → {boolean}
Checks if value
is classified as a Function
object.
Example
_.isFunction(_);
// => true
_.isFunction(/abc/);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isInteger(value) → {boolean}
Checks if value
is an integer.
Note: This method is based on Number.isInteger
.
Example
_.isInteger(3);
// => true
_.isInteger(Number.MIN_VALUE);
// => false
_.isInteger(Infinity);
// => false
_.isInteger('3');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is an integer, else false
.
- Type
- boolean
(static) isLength(value) → {boolean}
- Source:
Checks if value
is a valid array-like length.
Note: This function is loosely based on ToLength
.
Example
_.isLength(3);
// => true
_.isLength(Number.MIN_VALUE);
// => false
_.isLength(Infinity);
// => false
_.isLength('3');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is a valid length, else false
.
- Type
- boolean
(static) isMap(value) → {boolean}
- Source:
Checks if value
is classified as a Map
object.
Example
_.isMap(new Map);
// => true
_.isMap(new WeakMap);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isMatch(object, source) → {boolean}
- Source:
Performs a partial deep comparison between object
and source
to
determine if object
contains equivalent property values. This method is
equivalent to a _.matches
function when source
is partially applied.
Note: This method supports comparing the same values as _.isEqual
.
Example
var object = { 'user': 'fred', 'age': 40 };
_.isMatch(object, { 'age': 40 });
// => true
_.isMatch(object, { 'age': 36 });
// => false
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to inspect. |
source |
Object | The object of property values to match. |
Returns:
Returns true
if object
is a match, else false
.
- Type
- boolean
(static) isMatchWith(object, source, customizeropt) → {boolean}
- Source:
This method is like _.isMatch
except that it accepts customizer
which
is invoked to compare values. If customizer
returns undefined
comparisons
are handled by the method instead. The customizer
is invoked with five
arguments: (objValue, srcValue, index|key, object, source).
Example
function isGreeting(value) {
return /^h(?:i|ello)$/.test(value);
}
function customizer(objValue, srcValue) {
if (isGreeting(objValue) && isGreeting(srcValue)) {
return true;
}
}
var object = { 'greeting': 'hello' };
var source = { 'greeting': 'hi' };
_.isMatchWith(object, source, customizer);
// => true
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The object to inspect. |
|
source |
Object | The object of property values to match. |
|
customizer |
function |
<optional> |
The function to customize comparisons. |
Returns:
Returns true
if object
is a match, else false
.
- Type
- boolean
(static) isNaN(value) → {boolean}
- Source:
Checks if value
is NaN
.
Note: This method is not the same as isNaN
which returns true
for undefined
and other non-numeric values.
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 value
is NaN
, else false
.
- Type
- boolean
(static) isNative(value) → {boolean}
- Source:
Checks if value
is a native function.
Example
_.isNative(Array.prototype.push);
// => true
_.isNative(_);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is a native function, else false
.
- Type
- boolean
(static) isNil(value) → {boolean}
- Source:
Checks if value
is null
or undefined
.
Example
_.isNil(null);
// => true
_.isNil(void 0);
// => true
_.isNil(NaN);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is nullish, else false
.
- Type
- boolean
(static) isNull(value) → {boolean}
- Source:
Checks if value
is null
.
Example
_.isNull(null);
// => true
_.isNull(void 0);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is null
, else false
.
- Type
- boolean
(static) isNumber(value) → {boolean}
- Source:
Checks if value
is classified as a Number
primitive or object.
Note: To exclude Infinity
, -Infinity
, and NaN
, which are classified
as numbers, use the _.isFinite
method.
Example
_.isNumber(3);
// => true
_.isNumber(Number.MIN_VALUE);
// => true
_.isNumber(Infinity);
// => true
_.isNumber('3');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isObject(value) → {boolean}
- Source:
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(_.noop);
// => true
_.isObject(null);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is an object, else false
.
- Type
- boolean
(static) isObjectLike(value) → {boolean}
- Source:
Checks if value
is object-like. A value is object-like if it's not null
and has a typeof
result of "object".
Example
_.isObjectLike({});
// => true
_.isObjectLike([1, 2, 3]);
// => true
_.isObjectLike(_.noop);
// => false
_.isObjectLike(null);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is object-like, else false
.
- Type
- boolean
(static) isPlainObject(value) → {boolean}
- Source:
Checks if value
is a plain object, that is, an object created by the
Object
constructor or one with a [[Prototype]]
of null
.
Example
function Foo() {
this.a = 1;
}
_.isPlainObject(new Foo);
// => false
_.isPlainObject([1, 2, 3]);
// => false
_.isPlainObject({ 'x': 0, 'y': 0 });
// => true
_.isPlainObject(Object.create(null));
// => true
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is a plain object, else false
.
- Type
- boolean
(static) isRegExp(value) → {boolean}
- Source:
Checks if value
is classified as a RegExp
object.
Example
_.isRegExp(/abc/);
// => true
_.isRegExp('/abc/');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isSafeInteger(value) → {boolean}
- Source:
Checks if value
is a safe integer. An integer is safe if it's an IEEE-754
double precision number which isn't the result of a rounded unsafe integer.
Note: This method is based on Number.isSafeInteger
.
Example
_.isSafeInteger(3);
// => true
_.isSafeInteger(Number.MIN_VALUE);
// => false
_.isSafeInteger(Infinity);
// => false
_.isSafeInteger('3');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is a safe integer, else false
.
- Type
- boolean
(static) isSet(value) → {boolean}
- Source:
Checks if value
is classified as a Set
object.
Example
_.isSet(new Set);
// => true
_.isSet(new WeakSet);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isString(value) → {boolean}
- Source:
Checks if value
is classified as a String
primitive or object.
Example
_.isString('abc');
// => true
_.isString(1);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isSymbol(value) → {boolean}
- Source:
Checks if value
is classified as a Symbol
primitive or object.
Example
_.isSymbol(Symbol.iterator);
// => true
_.isSymbol('abc');
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isTypedArray(value) → {boolean}
- Source:
Checks if value
is classified as a typed array.
Example
_.isTypedArray(new Uint8Array);
// => true
_.isTypedArray([]);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isUndefined(value) → {boolean}
- Source:
Checks if value
is undefined
.
Example
_.isUndefined(void 0);
// => true
_.isUndefined(null);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is undefined
, else false
.
- Type
- boolean
(static) isWeakMap(value) → {boolean}
- Source:
Checks if value
is classified as a WeakMap
object.
Example
_.isWeakMap(new WeakMap);
// => true
_.isWeakMap(new Map);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) isWeakSet(value) → {boolean}
- Source:
Checks if value
is classified as a WeakSet
object.
Example
_.isWeakSet(new WeakSet);
// => true
_.isWeakSet(new Set);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to check. |
Returns:
Returns true
if value
is correctly classified, else false
.
- Type
- boolean
(static) iteratee(funcopt) → {function}
- Source:
Creates a function that invokes func
with the arguments of the created
function. If func
is a property name the created callback returns the
property value for a given element. If func
is an object the created
callback returns true
for elements that contain the equivalent object
properties, otherwise it returns false
.
Example
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
// Create custom iteratee shorthands.
_.iteratee = _.wrap(_.iteratee, function(callback, func) {
var p = /^(\S+)\s*([<>])\s*(\S+)$/.exec(func);
return !p ? callback(func) : function(object) {
return (p[2] == '>' ? object[p[1]] > p[3] : object[p[1]] < p[3]);
};
});
_.filter(users, 'age > 36');
// => [{ 'user': 'fred', 'age': 40 }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
* |
<optional> |
_.identity | The value to convert to a callback. |
Returns:
Returns the callback.
- Type
- function
(static) join(array, separatoropt) → {string}
Converts all elements in array
into a string separated by separator
.
Example
_.join(['a', 'b', 'c'], '~');
// => 'a~b~c'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to convert. |
||
separator |
string |
<optional> |
',' | The element separator. |
Returns:
Returns the joined string.
- Type
- string
(static) keys(object) → {Array}
- Source:
Creates an array of the own enumerable property names of object
.
Note: Non-object values are coerced to objects. See the ES spec for more details.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.keys(new Foo);
// => ['a', 'b'] (iteration order is not guaranteed)
_.keys('hi');
// => ['0', '1']
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
Returns:
Returns the array of property names.
- Type
- Array
(static) keysIn(object) → {Array}
- Source:
Creates an array of the own and inherited enumerable property names of object
.
Note: Non-object values are coerced to objects.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.keysIn(new Foo);
// => ['a', 'b', 'c'] (iteration order is not guaranteed)
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
Returns:
Returns the array of property names.
- Type
- Array
(static) last(array) → {*}
Gets the last element of array
.
Example
_.last([1, 2, 3]);
// => 3
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to query. |
Returns:
Returns the last element of array
.
- Type
- *
(static) lastIndexOf(array, value, fromIndexopt) → {number}
This method is like _.indexOf
except that it iterates over elements of
array
from right to left.
Example
_.lastIndexOf([1, 2, 1, 2], 2);
// => 3
// Search from the `fromIndex`.
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// => 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, else -1
.
- Type
- number
(static) lt(value, other) → {boolean}
- Source:
Checks if value
is less than other
.
Example
_.lt(1, 3);
// => true
_.lt(3, 3);
// => false
_.lt(3, 1);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to compare. |
other |
* | The other value to compare. |
Returns:
Returns true
if value
is less than other
, else false
.
- Type
- boolean
(static) lte(value, other) → {boolean}
- Source:
Checks if value
is less than or equal to other
.
Example
_.lte(1, 3);
// => true
_.lte(3, 3);
// => true
_.lte(3, 1);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to compare. |
other |
* | The other value to compare. |
Returns:
Returns true
if value
is less than or equal to other
, else false
.
- Type
- boolean
(static) map(collection, iterateeopt) → {Array}
Creates an array of values by running each element in collection
through
iteratee
. The iteratee is invoked with three arguments:
(value, index|key, collection).
Many lodash methods are guarded to work as iteratees for methods like
_.every
, _.filter
, _.map
, _.mapValues
, _.reject
, and _.some
.
The guarded methods are:
ary
, curry
, curryRight
, drop
, dropRight
, every
, fill
,
invert
, parseInt
, random
, range
, rangeRight
, slice
, some
,
sortBy
, take
, takeRight
, template
, trim
, trimEnd
, trimStart
,
and words
Example
function square(n) {
return n * n;
}
_.map([4, 8], square);
// => [16, 64]
_.map({ 'a': 4, 'b': 8 }, square);
// => [16, 64] (iteration order is not guaranteed)
var users = [
{ 'user': 'barney' },
{ 'user': 'fred' }
];
// The `_.property` iteratee shorthand.
_.map(users, 'user');
// => ['barney', 'fred']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the new mapped array.
- Type
- Array
(static) mapKeys(object, iterateeopt) → {Object}
- Source:
The opposite of _.mapValues
; this method creates an object with the
same values as object
and keys generated by running each own enumerable
property of object
through iteratee
. The iteratee is invoked with
three arguments: (value, key, object).
Example
_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
return key + value;
});
// => { 'a1': 1, 'b2': 2 }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the new mapped object.
- Type
- Object
(static) mapValues(object, iterateeopt) → {Object}
- Source:
Creates an object with the same keys as object
and values generated by
running each own enumerable property of object
through iteratee
. The
iteratee is invoked with three arguments: (value, key, object).
Example
var users = {
'fred': { 'user': 'fred', 'age': 40 },
'pebbles': { 'user': 'pebbles', 'age': 1 }
};
_.mapValues(users, function(o) { return o.age; });
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
// The `_.property` iteratee shorthand.
_.mapValues(users, 'age');
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The object to iterate over. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the new mapped object.
- Type
- Object
(static) matches(source) → {function}
- Source:
Creates a function that performs a partial deep comparison between a given
object and source
, returning true
if the given object has equivalent
property values, else false
. The created function is equivalent to
_.isMatch
with a source
partially applied.
Note: This method supports comparing the same values as _.isEqual
.
Example
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(users, _.matches({ 'age': 40, 'active': false }));
// => [{ 'user': 'fred', 'age': 40, 'active': false }]
Parameters:
Name | Type | Description |
---|---|---|
source |
Object | The object of property values to match. |
Returns:
Returns the new function.
- Type
- function
(static) matchesProperty(path, srcValue) → {function}
- Source:
Creates a function that performs a partial deep comparison between the
value at path
of a given object to srcValue
, returning true
if the
object value is equivalent, else false
.
Note: This method supports comparing the same values as _.isEqual
.
Example
var users = [
{ 'user': 'barney' },
{ 'user': 'fred' }
];
_.find(users, _.matchesProperty('user', 'fred'));
// => { 'user': 'fred' }
Parameters:
Name | Type | Description |
---|---|---|
path |
Array | string | The path of the property to get. |
srcValue |
* | The value to match. |
Returns:
Returns the new function.
- Type
- function
(static) max(array) → {*}
- Source:
Computes the maximum value of array
. If array
is empty or falsey
undefined
is returned.
Example
_.max([4, 2, 8, 6]);
// => 8
_.max([]);
// => undefined
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to iterate over. |
Returns:
Returns the maximum value.
- Type
- *
(static) maxBy(array, iterateeopt) → {*}
- Source:
This method is like _.max
except that it accepts iteratee
which is
invoked for each element in array
to generate the criterion by which
the value is ranked. The iteratee is invoked with one argument: (value).
Example
var objects = [{ 'n': 1 }, { 'n': 2 }];
_.maxBy(objects, function(o) { return o.n; });
// => { 'n': 2 }
// The `_.property` iteratee shorthand.
_.maxBy(objects, 'n');
// => { 'n': 2 }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to iterate over. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The iteratee invoked per element. |
Returns:
Returns the maximum value.
- Type
- *
(static) mean(array) → {number}
- Source:
Computes the mean of the values in array
.
Example
_.mean([4, 2, 8, 6]);
// => 5
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to iterate over. |
Returns:
Returns the mean.
- Type
- number
(static) memoize(func, resolveropt) → {function}
Creates a function that memoizes the result of func
. If resolver
is
provided it determines the cache key for storing the result based on the
arguments provided to the memoized function. By default, the first argument
provided to the memoized function is used as the map cache key. The func
is invoked with the this
binding of the memoized function.
Note: The cache is exposed as the cache
property on the memoized
function. Its creation may be customized by replacing the _.memoize.Cache
constructor with one whose instances implement the Map
method interface of delete
, get
, has
, and set
.
Example
var object = { 'a': 1, 'b': 2 };
var other = { 'c': 3, 'd': 4 };
var values = _.memoize(_.values);
values(object);
// => [1, 2]
values(other);
// => [3, 4]
object.a = 2;
values(object);
// => [1, 2]
// Modify the result cache.
values.cache.set(object, ['a', 'b']);
values(object);
// => ['a', 'b']
// Replace `_.memoize.Cache`.
_.memoize.Cache = WeakMap;
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
func |
function | The function to have its output memoized. |
|
resolver |
function |
<optional> |
The function to resolve the cache key. |
Returns:
Returns the new memoizing function.
- Type
- function
(static) min(array) → {*}
- Source:
Computes the minimum value of array
. If array
is empty or falsey
undefined
is returned.
Example
_.min([4, 2, 8, 6]);
// => 2
_.min([]);
// => undefined
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to iterate over. |
Returns:
Returns the minimum value.
- Type
- *
(static) minBy(array, iterateeopt) → {*}
- Source:
This method is like _.min
except that it accepts iteratee
which is
invoked for each element in array
to generate the criterion by which
the value is ranked. The iteratee is invoked with one argument: (value).
Example
var objects = [{ 'n': 1 }, { 'n': 2 }];
_.minBy(objects, function(o) { return o.n; });
// => { 'n': 1 }
// The `_.property` iteratee shorthand.
_.minBy(objects, 'n');
// => { 'n': 1 }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to iterate over. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The iteratee invoked per element. |
Returns:
Returns the minimum value.
- Type
- *
(static) mixin(objectopt, source, optionsopt) → {function|Object}
- Source:
Adds all own enumerable function properties of a source object to the
destination object. If object
is a function then methods are added to
its prototype as well.
Note: Use _.runInContext
to create a pristine lodash
function to
avoid conflicts caused by modifying the original.
Example
function vowels(string) {
return _.filter(string, function(v) {
return /[aeiou]/i.test(v);
});
}
_.mixin({ 'vowels': vowels });
_.vowels('fred');
// => ['e']
_('fred').vowels().value();
// => ['e']
_.mixin({ 'vowels': vowels }, { 'chain': false });
_('fred').vowels();
// => ['e']
Parameters:
Name | Type | Attributes | Default | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
object |
function | Object |
<optional> |
lodash | The destination object. |
||||||||||
source |
Object | The object of functions to add. |
||||||||||||
options |
Object |
<optional> |
The options object. Properties
|
Returns:
Returns object
.
- Type
- function | Object
(static) negate(predicate) → {function}
Creates a function that negates the result of the predicate func
. The
func
predicate is invoked with the this
binding and arguments of the
created function.
Example
function isEven(n) {
return n % 2 == 0;
}
_.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
// => [1, 3, 5]
Parameters:
Name | Type | Description |
---|---|---|
predicate |
function | The predicate to negate. |
Returns:
Returns the new function.
- Type
- function
(static) noConflict() → {function}
- Source:
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) noop()
- Source:
A no-operation function that returns undefined
regardless of the
arguments it receives.
Example
var object = { 'user': 'fred' };
_.noop(object) === undefined;
// => true
(static) nthArg(nopt) → {function}
- Source:
Creates a function that returns its nth argument.
Example
var func = _.nthArg(1);
func('a', 'b', 'c');
// => 'b'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
n |
number |
<optional> |
0 | The index of the argument to return. |
Returns:
Returns the new function.
- Type
- function
(static) omitBy(object, predicateopt) → {Object}
- Source:
The opposite of _.pickBy
; this method creates an object composed of
the own and inherited enumerable properties of object
that predicate
doesn't return truthy for. The predicate is invoked with two arguments:
(value, key).
Example
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.omitBy(object, _.isNumber);
// => { 'b': '2' }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The source object. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per property. |
Returns:
Returns the new object.
- Type
- Object
(static) once(func) → {function}
Creates a function that is restricted to invoking func
once. Repeat calls
to the function return the value of the first invocation. The func
is
invoked with the this
binding and arguments of the created function.
Example
var initialize = _.once(createApplication);
initialize();
initialize();
// `initialize` invokes `createApplication` once
Parameters:
Name | Type | Description |
---|---|---|
func |
function | The function to restrict. |
Returns:
Returns the new restricted function.
- Type
- function
(static) orderBy(collection, iterateesopt, ordersopt) → {Array}
This method is like _.sortBy
except that it allows specifying the sort
orders of the iteratees to sort by. If orders
is unspecified, all values
are sorted in ascending order. Otherwise, specify an order of "desc" for
descending or "asc" for ascending sort order of corresponding values.
Example
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 34 },
{ 'user': 'fred', 'age': 42 },
{ 'user': 'barney', 'age': 36 }
];
// Sort by `user` in ascending order and by `age` in descending order.
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
iteratees |
Array.<function()> | Array.<Object> | Array.<string> |
<optional> |
[_.identity] | The iteratees to sort by. |
orders |
Array.<string> |
<optional> |
The sort orders of |
Returns:
Returns the new sorted array.
- Type
- Array
(static) pad(stringopt, lengthopt, charsopt) → {string}
- Source:
Pads string
on the left and right sides if it's shorter than length
.
Padding characters are truncated if they can't be evenly divided by length
.
Example
_.pad('abc', 8);
// => ' abc '
_.pad('abc', 8, '_-');
// => '_-abc_-_'
_.pad('abc', 3);
// => 'abc'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to pad. |
length |
number |
<optional> |
0 | The padding length. |
chars |
string |
<optional> |
' ' | The string used as padding. |
Returns:
Returns the padded string.
- Type
- string
(static) padEnd(stringopt, lengthopt, charsopt) → {string}
- Source:
Pads string
on the right side if it's shorter than length
. Padding
characters are truncated if they exceed length
.
Example
_.padEnd('abc', 6);
// => 'abc '
_.padEnd('abc', 6, '_-');
// => 'abc_-_'
_.padEnd('abc', 3);
// => 'abc'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to pad. |
length |
number |
<optional> |
0 | The padding length. |
chars |
string |
<optional> |
' ' | The string used as padding. |
Returns:
Returns the padded string.
- Type
- string
(static) padStart(stringopt, lengthopt, charsopt) → {string}
- Source:
Pads string
on the left side if it's shorter than length
. Padding
characters are truncated if they exceed length
.
Example
_.padStart('abc', 6);
// => ' abc'
_.padStart('abc', 6, '_-');
// => '_-_abc'
_.padStart('abc', 3);
// => 'abc'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to pad. |
length |
number |
<optional> |
0 | The padding length. |
chars |
string |
<optional> |
' ' | The string used as padding. |
Returns:
Returns the padded string.
- Type
- string
(static) parseInt(string, radixopt) → {number}
- Source:
Converts string
to an integer of the specified radix. If radix
is
undefined
or 0
, a radix
of 10
is used unless value
is a hexadecimal,
in which case a radix
of 16
is used.
Note: This method aligns with the ES5 implementation
of parseInt
.
Example
_.parseInt('08');
// => 8
_.map(['6', '08', '10'], _.parseInt);
// => [6, 8, 10]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string | The string to convert. |
||
radix |
number |
<optional> |
10 | The radix to interpret |
Returns:
Returns the converted integer.
- Type
- number
(static) pickBy(object, predicateopt) → {Object}
- Source:
Creates an object composed of the object
properties predicate
returns
truthy for. The predicate is invoked with two arguments: (value, key).
Example
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.pickBy(object, _.isNumber);
// => { 'a': 1, 'c': 3 }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Object | The source object. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per property. |
Returns:
Returns the new object.
- Type
- Object
(static) property(path) → {function}
- Source:
Creates a function that returns the value at path
of a given object.
Example
var objects = [
{ 'a': { 'b': { 'c': 2 } } },
{ 'a': { 'b': { 'c': 1 } } }
];
_.map(objects, _.property('a.b.c'));
// => [2, 1]
_.map(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
// => [1, 2]
Parameters:
Name | Type | Description |
---|---|---|
path |
Array | string | The path of the property to get. |
Returns:
Returns the new function.
- Type
- function
(static) propertyOf(object) → {function}
- Source:
The opposite of _.property
; this method creates a function that returns
the value at a given path of object
.
Example
var array = [0, 1, 2],
object = { 'a': array, 'b': array, 'c': array };
_.map(['a[2]', 'c[0]'], _.propertyOf(object));
// => [2, 0]
_.map([['a', '2'], ['c', '0']], _.propertyOf(object));
// => [2, 0]
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
Returns:
Returns the new function.
- Type
- function
(static) pullAll(array, values) → {Array}
This method is like _.pull
except that it accepts an array of values to remove.
Note: Unlike _.difference
, this method mutates array
.
Example
var array = [1, 2, 3, 1, 2, 3];
_.pullAll(array, [2, 3]);
console.log(array);
// => [1, 1]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to modify. |
values |
Array | The values to remove. |
Returns:
Returns array
.
- Type
- Array
(static) pullAllBy(array, values, iterateeopt) → {Array}
This method is like _.pullAll
except that it accepts iteratee
which is
invoked for each element of array
and values
to generate the criterion
by which uniqueness is computed. The iteratee is invoked with one argument: (value).
Note: Unlike _.differenceBy
, this method mutates array
.
Example
var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
_.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
console.log(array);
// => [{ 'x': 2 }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to modify. |
||
values |
Array | The values to remove. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The iteratee invoked per element. |
Returns:
Returns array
.
- Type
- Array
(static) random(loweropt, upperopt, floatingopt) → {number}
- Source:
Produces a random number between the inclusive lower
and upper
bounds.
If only one argument is provided a number between 0
and the given number
is returned. If floating
is true
, or either lower
or upper
are floats,
a floating-point number is returned instead of an integer.
Note: JavaScript follows the IEEE-754 standard for resolving floating-point values which can produce unexpected results.
Example
_.random(0, 5);
// => an integer between 0 and 5
_.random(5);
// => also an integer between 0 and 5
_.random(5, true);
// => a floating-point number between 0 and 5
_.random(1.2, 5.2);
// => a floating-point number between 1.2 and 5.2
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
lower |
number |
<optional> |
0 | The lower bound. |
upper |
number |
<optional> |
1 | The upper bound. |
floating |
boolean |
<optional> |
Specify returning a floating-point number. |
Returns:
Returns the random number.
- Type
- number
(static) reduce(collection, iterateeopt, accumulatoropt) → {*}
Reduces collection
to a value which is the accumulated result of running
each element in collection
through iteratee
, where each successive
invocation is supplied the return value of the previous. If accumulator
is not given the first element of collection
is used as the initial
value. The iteratee is invoked with four arguments:
(accumulator, value, index|key, collection).
Many lodash methods are guarded to work as iteratees for methods like
_.reduce
, _.reduceRight
, and _.transform
.
The guarded methods are:
assign
, defaults
, defaultsDeep
, includes
, merge
, orderBy
,
and sortBy
Example
_.reduce([1, 2], function(sum, n) {
return sum + n;
}, 0);
// => 3
_.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
(result[value] || (result[value] = [])).push(key);
return result;
}, {});
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
accumulator |
* |
<optional> |
The initial value. |
Returns:
Returns the accumulated value.
- Type
- *
(static) reduceRight(collection, iterateeopt, accumulatoropt) → {*}
This method is like _.reduce
except that it iterates over elements of
collection
from right to left.
Example
var array = [[0, 1], [2, 3], [4, 5]];
_.reduceRight(array, function(flattened, other) {
return flattened.concat(other);
}, []);
// => [4, 5, 2, 3, 0, 1]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
accumulator |
* |
<optional> |
The initial value. |
Returns:
Returns the accumulated value.
- Type
- *
(static) reject(collection, predicateopt) → {Array}
The opposite of _.filter
; this method returns the elements of collection
that predicate
does not return truthy for.
Example
var users = [
{ 'user': 'barney', 'age': 36, 'active': false },
{ 'user': 'fred', 'age': 40, 'active': true }
];
_.reject(users, function(o) { return !o.active; });
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.reject(users, { 'age': 40, 'active': true });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.reject(users, ['active', false]);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.reject(users, 'active');
// => objects for ['barney']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the new filtered array.
- Type
- Array
(static) remove(array, predicateopt) → {Array}
Removes all elements from array
that predicate
returns truthy for
and returns an array of the removed elements. The predicate is invoked
with three arguments: (value, index, array).
Note: Unlike _.filter
, this method mutates array
. Use _.pull
to pull elements from an array by value.
Example
var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
return n % 2 == 0;
});
console.log(array);
// => [1, 3]
console.log(evens);
// => [2, 4]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to modify. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the new array of removed elements.
- Type
- Array
(static) repeat(stringopt, nopt) → {string}
- Source:
Repeats the given string n
times.
Example
_.repeat('*', 3);
// => '***'
_.repeat('abc', 2);
// => 'abcabc'
_.repeat('abc', 0);
// => ''
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to repeat. |
n |
number |
<optional> |
0 | The number of times to repeat the string. |
Returns:
Returns the repeated string.
- Type
- string
(static) replace(stringopt, pattern, replacement) → {string}
- Source:
Replaces matches for pattern
in string
with replacement
.
Note: This method is based on String#replace
.
Example
_.replace('Hi Fred', 'Fred', 'Barney');
// => 'Hi Barney'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to modify. |
pattern |
RegExp | string | The pattern to replace. |
||
replacement |
function | string | The match replacement. |
Returns:
Returns the modified string.
- Type
- string
(static) rest(func, startopt) → {function}
Creates a function that invokes func
with the this
binding of the
created function and arguments from start
and beyond provided as an array.
Note: This method is based on the rest parameter.
Example
var say = _.rest(function(what, names) {
return what + ' ' + _.initial(names).join(', ') +
(_.size(names) > 1 ? ', & ' : '') + _.last(names);
});
say('hello', 'fred', 'barney', 'pebbles');
// => 'hello fred, barney, & pebbles'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
function | The function to apply a rest parameter to. |
||
start |
number |
<optional> |
func.length-1 | The start position of the rest parameter. |
Returns:
Returns the new function.
- Type
- function
(static) result(object, path, defaultValueopt) → {*}
- Source:
This method is like _.get
except that if the resolved value is a function
it's invoked with the this
binding of its parent object and its result
is returned.
Example
var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
_.result(object, 'a[0].b.c1');
// => 3
_.result(object, 'a[0].b.c2');
// => 4
_.result(object, 'a[0].b.c3', 'default');
// => 'default'
_.result(object, 'a[0].b.c3', _.constant('default'));
// => 'default'
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The object to query. |
|
path |
Array | string | The path of the property to resolve. |
|
defaultValue |
* |
<optional> |
The value returned if the resolved value is |
Returns:
Returns the resolved value.
- Type
- *
(static) reverse() → {Array}
Reverses array
so that the first element becomes the last, the second
element becomes the second to last, and so on.
Note: This method mutates array
and is based on
Array#reverse
.
Example
var array = [1, 2, 3];
_.reverse(array);
// => [3, 2, 1]
console.log(array);
// => [3, 2, 1]
Returns:
Returns array
.
- Type
- Array
(static) runInContext(contextopt) → {function}
Create a new pristine lodash
function using the context
object.
Example
_.mixin({ 'foo': _.constant('foo') });
var lodash = _.runInContext();
lodash.mixin({ 'bar': lodash.constant('bar') });
_.isFunction(_.foo);
// => true
_.isFunction(_.bar);
// => false
lodash.isFunction(lodash.foo);
// => false
lodash.isFunction(lodash.bar);
// => true
// Use `context` to mock `Date#getTime` use in `_.now`.
var mock = _.runInContext({
'Date': function() {
return { 'getTime': getTimeMock };
}
});
// Create a suped-up `defer` in Node.js.
var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
context |
Object |
<optional> |
root | The context object. |
Returns:
Returns a new lodash
function.
- Type
- function
(static) sample(collection) → {*}
Gets a random element from collection
.
Example
_.sample([1, 2, 3, 4]);
// => 2
Parameters:
Name | Type | Description |
---|---|---|
collection |
Array | Object | The collection to sample. |
Returns:
Returns the random element.
- Type
- *
(static) sampleSize(collection, nopt) → {Array}
Gets n
random elements at unique keys from collection
up to the
size of collection
.
Example
_.sampleSize([1, 2, 3], 2);
// => [3, 1]
_.sampleSize([1, 2, 3], 4);
// => [2, 3, 1]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to sample. |
||
n |
number |
<optional> |
0 | The number of elements to sample. |
Returns:
Returns the random elements.
- Type
- Array
(static) set(object, path, value) → {Object}
- Source:
Sets the value at path
of object
. If a portion of path
doesn't exist
it's created. Arrays are created for missing index properties while objects
are created for all other missing properties. Use _.setWith
to customize
path
creation.
Note: This method mutates object
.
Example
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
_.set(object, 'x[0].y.z', 5);
console.log(object.x[0].y.z);
// => 5
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to modify. |
path |
Array | string | The path of the property to set. |
value |
* | The value to set. |
Returns:
Returns object
.
- Type
- Object
(static) setWith(object, path, value, customizeropt) → {Object}
- Source:
This method is like _.set
except that it accepts customizer
which is
invoked to produce the objects of path
. If customizer
returns undefined
path creation is handled by the method instead. The customizer
is invoked
with three arguments: (nsValue, key, nsObject).
Note: This method mutates object
.
Example
_.setWith({ '0': { 'length': 2 } }, '[0][1][2]', 3, Object);
// => { '0': { '1': { '2': 3 }, 'length': 2 } }
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
object |
Object | The object to modify. |
|
path |
Array | string | The path of the property to set. |
|
value |
* | The value to set. |
|
customizer |
function |
<optional> |
The function to customize assigned values. |
Returns:
Returns object
.
- Type
- Object
(static) shuffle(collection) → {Array}
Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.
Example
_.shuffle([1, 2, 3, 4]);
// => [4, 1, 3, 2]
Parameters:
Name | Type | Description |
---|---|---|
collection |
Array | Object | The collection to shuffle. |
Returns:
Returns the new shuffled array.
- Type
- Array
(static) size(collection) → {number}
Gets the size of collection
by returning its length for array-like
values or the number of own enumerable properties for objects.
Example
_.size([1, 2, 3]);
// => 3
_.size({ 'a': 1, 'b': 2 });
// => 2
_.size('pebbles');
// => 7
Parameters:
Name | Type | Description |
---|---|---|
collection |
Array | Object | The collection to inspect. |
Returns:
Returns the collection size.
- Type
- number
(static) slice(array, startopt, endopt) → {Array}
Creates a slice of array
from start
up to, but not including, end
.
Note: This method is used instead of Array#slice
to ensure dense arrays are returned.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to slice. |
||
start |
number |
<optional> |
0 | The start position. |
end |
number |
<optional> |
array.length | The end position. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) some(collection, predicateopt) → {boolean}
Checks if predicate
returns truthy for any element of collection
.
Iteration is stopped once predicate
returns truthy. The predicate is
invoked with three arguments: (value, index|key, collection).
Example
_.some([null, 0, 'yes', false], Boolean);
// => true
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false }
];
// The `_.matches` iteratee shorthand.
_.some(users, { 'user': 'barney', 'active': false });
// => false
// The `_.matchesProperty` iteratee shorthand.
_.some(users, ['active', false]);
// => true
// The `_.property` iteratee shorthand.
_.some(users, 'active');
// => true
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
collection |
Array | Object | The collection to iterate over. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns true
if any element passes the predicate check, else false
.
- Type
- boolean
(static) sortedIndex(array, value) → {number}
Uses a binary search to determine the lowest index at which value
should
be inserted into array
in order to maintain its sort order.
Example
_.sortedIndex([30, 50], 40);
// => 1
_.sortedIndex([4, 5], 4);
// => 0
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The sorted array to inspect. |
value |
* | The value to evaluate. |
Returns:
Returns the index at which value
should be inserted into array
.
- Type
- number
(static) sortedIndexBy(array, value, iterateeopt) → {number}
This method is like _.sortedIndex
except that it accepts iteratee
which is invoked for value
and each element of array
to compute their
sort ranking. The iteratee is invoked with one argument: (value).
Example
var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 };
_.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict));
// => 1
// The `_.property` iteratee shorthand.
_.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
// => 0
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The sorted array to inspect. |
||
value |
* | The value to evaluate. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The iteratee invoked per element. |
Returns:
Returns the index at which value
should be inserted into array
.
- Type
- number
(static) sortedIndexOf(array, value) → {number}
This method is like _.indexOf
except that it performs a binary
search on a sorted array
.
Example
_.sortedIndexOf([1, 1, 2, 2], 2);
// => 2
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to search. |
value |
* | The value to search for. |
Returns:
Returns the index of the matched value, else -1
.
- Type
- number
(static) sortedLastIndex(array, value) → {number}
This method is like _.sortedIndex
except that it returns the highest
index at which value
should be inserted into array
in order to
maintain its sort order.
Example
_.sortedLastIndex([4, 5], 4);
// => 1
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The sorted array to inspect. |
value |
* | The value to evaluate. |
Returns:
Returns the index at which value
should be inserted into array
.
- Type
- number
(static) sortedLastIndexBy(array, value, iterateeopt) → {number}
This method is like _.sortedLastIndex
except that it accepts iteratee
which is invoked for value
and each element of array
to compute their
sort ranking. The iteratee is invoked with one argument: (value).
Example
// The `_.property` iteratee shorthand.
_.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
// => 1
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The sorted array to inspect. |
||
value |
* | The value to evaluate. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The iteratee invoked per element. |
Returns:
Returns the index at which value
should be inserted into array
.
- Type
- number
(static) sortedLastIndexOf(array, value) → {number}
This method is like _.lastIndexOf
except that it performs a binary
search on a sorted array
.
Example
_.sortedLastIndexOf([1, 1, 2, 2], 2);
// => 3
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to search. |
value |
* | The value to search for. |
Returns:
Returns the index of the matched value, else -1
.
- Type
- number
(static) sortedUniq(array) → {Array}
This method is like _.uniq
except that it's designed and optimized
for sorted arrays.
Example
_.sortedUniq([1, 1, 2]);
// => [1, 2]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to inspect. |
Returns:
Returns the new duplicate free array.
- Type
- Array
(static) sortedUniqBy(array, iterateeopt) → {Array}
This method is like _.uniqBy
except that it's designed and optimized
for sorted arrays.
Example
_.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
// => [1.1, 2.3]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array | The array to inspect. |
|
iteratee |
function |
<optional> |
The iteratee invoked per element. |
Returns:
Returns the new duplicate free array.
- Type
- Array
(static) split(stringopt, separator, limitopt) → {Array}
- Source:
Splits string
by separator
.
Note: This method is based on String#split
.
Example
_.split('a-b-c', '-', 2);
// => ['a', 'b']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to split. |
separator |
RegExp | string | The separator pattern to split by. |
||
limit |
number |
<optional> |
The length to truncate results to. |
Returns:
Returns the new array of string segments.
- Type
- Array
(static) spread(func, startopt) → {function}
Creates a function that invokes func
with the this
binding of the created
function and an array of arguments much like Function#apply
.
Note: This method is based on the spread operator.
Example
var say = _.spread(function(who, what) {
return who + ' says ' + what;
});
say(['fred', 'hello']);
// => 'fred says hello'
var numbers = Promise.all([
Promise.resolve(40),
Promise.resolve(36)
]);
numbers.then(_.spread(function(x, y) {
return x + y;
}));
// => a Promise of 76
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
function | The function to spread arguments over. |
||
start |
number |
<optional> |
0 | The start position of the spread. |
Returns:
Returns the new function.
- Type
- function
(static) startsWith(stringopt, targetopt, positionopt) → {boolean}
- Source:
Checks if string
starts with the given target string.
Example
_.startsWith('abc', 'a');
// => true
_.startsWith('abc', 'b');
// => false
_.startsWith('abc', 'b', 1);
// => true
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to search. |
target |
string |
<optional> |
The string to search for. |
|
position |
number |
<optional> |
0 | The position to search from. |
Returns:
Returns true
if string
starts with target
, else false
.
- Type
- boolean
(static) subtract(minuend, subtrahend) → {number}
- Source:
Subtract two numbers.
Example
_.subtract(6, 4);
// => 2
Parameters:
Name | Type | Description |
---|---|---|
minuend |
number | The first number in a subtraction. |
subtrahend |
number | The second number in a subtraction. |
Returns:
Returns the difference.
- Type
- number
(static) sum(array) → {number}
- Source:
Computes the sum of the values in array
.
Example
_.sum([4, 2, 8, 6]);
// => 20
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to iterate over. |
Returns:
Returns the sum.
- Type
- number
(static) sumBy(array, iterateeopt) → {number}
- Source:
This method is like _.sum
except that it accepts iteratee
which is
invoked for each element in array
to generate the value to be summed.
The iteratee is invoked with one argument: (value).
Example
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.sumBy(objects, function(o) { return o.n; });
// => 20
// The `_.property` iteratee shorthand.
_.sumBy(objects, 'n');
// => 20
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to iterate over. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The iteratee invoked per element. |
Returns:
Returns the sum.
- Type
- number
(static) tail(array) → {Array}
Gets all but the first element of array
.
Example
_.tail([1, 2, 3]);
// => [2, 3]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to query. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) take(array, nopt) → {Array}
Creates a slice of array
with n
elements taken from the beginning.
Example
_.take([1, 2, 3]);
// => [1]
_.take([1, 2, 3], 2);
// => [1, 2]
_.take([1, 2, 3], 5);
// => [1, 2, 3]
_.take([1, 2, 3], 0);
// => []
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
n |
number |
<optional> |
1 | The number of elements to take. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) takeRight(array, nopt) → {Array}
Creates a slice of array
with n
elements taken from the end.
Example
_.takeRight([1, 2, 3]);
// => [3]
_.takeRight([1, 2, 3], 2);
// => [2, 3]
_.takeRight([1, 2, 3], 5);
// => [1, 2, 3]
_.takeRight([1, 2, 3], 0);
// => []
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
n |
number |
<optional> |
1 | The number of elements to take. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) takeRightWhile(array, predicateopt) → {Array}
Creates a slice of array
with elements taken from the end. Elements are
taken until predicate
returns falsey. The predicate is invoked with three
arguments: (value, index, array).
Example
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': false }
];
_.takeRightWhile(users, function(o) { return !o.active; });
// => objects for ['fred', 'pebbles']
// The `_.matches` iteratee shorthand.
_.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
// => objects for ['pebbles']
// The `_.matchesProperty` iteratee shorthand.
_.takeRightWhile(users, ['active', false]);
// => objects for ['fred', 'pebbles']
// The `_.property` iteratee shorthand.
_.takeRightWhile(users, 'active');
// => []
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) takeWhile(array, predicateopt) → {Array}
Creates a slice of array
with elements taken from the beginning. Elements
are taken until predicate
returns falsey. The predicate is invoked with
three arguments: (value, index, array).
Example
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false},
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to query. |
||
predicate |
function | Object | string |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the slice of array
.
- Type
- Array
(static) tap(value, interceptor) → {*}
This method invokes interceptor
and returns value
. The interceptor
is invoked with one argument; (value). The purpose of this method is to
"tap into" a method chain in order to modify intermediate results.
Example
_([1, 2, 3])
.tap(function(array) {
// Mutate input array.
array.pop();
})
.reverse()
.value();
// => [2, 1]
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to provide to |
interceptor |
function | The function to invoke. |
Returns:
Returns value
.
- Type
- *
(static) template(stringopt, optionsopt) → {function}
- Source:
Creates a compiled template function that can interpolate data properties
in "interpolate" delimiters, HTML-escape interpolated data properties in
"escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
properties may be accessed as free variables in the template. If a setting
object is given it takes precedence over _.templateSettings
values.
Note: In the development build _.template
utilizes
sourceURLs
for easier debugging.
For more information on precompiling templates see lodash's custom builds documentation.
For more information on Chrome extension sandboxes see Chrome's extensions documentation.
Example
// Use the "interpolate" delimiter to create a compiled template.
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'
// Use the HTML "escape" delimiter to escape data property values.
var compiled = _.template('<b><%- value %></b>');
compiled({ 'value': '<script>' });
// => '<b><script></b>'
// Use the "evaluate" delimiter to execute JavaScript and generate HTML.
var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
compiled({ 'users': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'
// Use the internal `print` function in "evaluate" delimiters.
var compiled = _.template('<% print("hello " + user); %>!');
compiled({ 'user': 'barney' });
// => 'hello barney!'
// Use the ES delimiter as an alternative to the default "interpolate" delimiter.
var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles!'
// Use custom template delimiters.
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'
// Use backslashes to treat delimiters as plain text.
var compiled = _.template('<%= "\\<%- value %\\>" %>');
compiled({ 'value': 'ignored' });
// => '<%- value %>'
// Use the `imports` option to import `jQuery` as `jq`.
var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
compiled({ 'users': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'
// Use the `sourceURL` option to specify a custom sourceURL for the template.
var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
compiled(data);
// => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
// Use the `variable` option to ensure a with-statement isn't used in the compiled template.
var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
compiled.source;
// => function(data) {
// var __t, __p = '';
// __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
// return __p;
// }
// Use the `source` property to inline compiled templates for meaningful
// line numbers in error messages and stack traces.
fs.writeFileSync(path.join(cwd, 'jst.js'), '\
var JST = {\
"main": ' + _.template(mainText).source + '\
};\
');
Parameters:
Name | Type | Attributes | Default | Description | ||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
string |
string |
<optional> |
'' | The template string. |
||||||||||||||||||||||||||||
options |
Object |
<optional> |
The options object. Properties
|
Returns:
Returns the compiled template function.
- Type
- function
(static) throttle(func, waitopt, optionsopt) → {function}
Creates a throttled function that only invokes func
at most once per
every wait
milliseconds. The throttled function comes with a cancel
method to cancel delayed func
invocations and a flush
method to
immediately invoke them. Provide an options object to indicate whether
func
should be invoked on the leading and/or trailing edge of the wait
timeout. The func
is invoked with the last arguments provided to the
throttled function. Subsequent calls to the throttled function return the
result of the last func
invocation.
Note: If leading
and trailing
options are true
, func
is invoked
on the trailing edge of the timeout only if the throttled function is
invoked more than once during the wait
timeout.
See David Corbacho's article
for details over the differences between _.throttle
and _.debounce
.
Example
// Avoid excessively updating the position while scrolling.
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
// Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
// Cancel the trailing throttled invocation.
jQuery(window).on('popstate', throttled.cancel);
Parameters:
Name | Type | Attributes | Default | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
func |
function | The function to throttle. |
|||||||||||||||||
wait |
number |
<optional> |
0 | The number of milliseconds to throttle invocations to. |
|||||||||||||||
options |
Object |
<optional> |
The options object. Properties
|
Returns:
Returns the new throttled function.
- Type
- function
(static) thru(value, interceptor) → {*}
This method is like _.tap
except that it returns the result of interceptor
.
The purpose of this method is to "pass thru" values replacing intermediate
results in a method chain.
Example
_(' abc ')
.chain()
.trim()
.thru(function(value) {
return [value];
})
.value();
// => ['abc']
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to provide to |
interceptor |
function | The function to invoke. |
Returns:
Returns the result of interceptor
.
- Type
- *
(static) times(n, iterateeopt) → {Array}
- Source:
Invokes the iteratee n
times, returning an array of the results of
each invocation. The iteratee is invoked with one argument; (index).
Example
_.times(3, String);
// => ['0', '1', '2']
_.times(4, _.constant(true));
// => [true, true, true, true]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
n |
number | The number of times to invoke |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
Returns:
Returns the array of results.
- Type
- Array
(static) toArray(value) → {Array}
- Source:
Converts value
to an array.
Example
_.toArray({ 'a': 1, 'b': 2 });
// => [1, 2]
_.toArray('abc');
// => ['a', 'b', 'c']
_.toArray(1);
// => []
_.toArray(null);
// => []
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to convert. |
Returns:
Returns the converted array.
- Type
- Array
(static) toInteger(value) → {number}
- Source:
Converts value
to an integer.
Note: This function is loosely based on ToInteger
.
Example
_.toInteger(3);
// => 3
_.toInteger(Number.MIN_VALUE);
// => 0
_.toInteger(Infinity);
// => 1.7976931348623157e+308
_.toInteger('3');
// => 3
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to convert. |
Returns:
Returns the converted integer.
- Type
- number
(static) toLength(value) → {number}
- Source:
Converts value
to an integer suitable for use as the length of an
array-like object.
Note: This method is based on ToLength
.
Example
_.toLength(3);
// => 3
_.toLength(Number.MIN_VALUE);
// => 0
_.toLength(Infinity);
// => 4294967295
_.toLength('3');
// => 3
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to convert. |
Returns:
Returns the converted integer.
- Type
- number
(static) toLower(stringopt) → {string}
- Source:
Converts string
, as a whole, to lower case.
Example
_.toLower('--Foo-Bar');
// => '--foo-bar'
_.toLower('fooBar');
// => 'foobar'
_.toLower('__FOO_BAR__');
// => '__foo_bar__'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to convert. |
Returns:
Returns the lower cased string.
- Type
- string
(static) toNumber(value) → {number}
- Source:
Converts value
to a number.
Example
_.toNumber(3);
// => 3
_.toNumber(Number.MIN_VALUE);
// => 5e-324
_.toNumber(Infinity);
// => Infinity
_.toNumber('3');
// => 3
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to process. |
Returns:
Returns the number.
- Type
- number
(static) toPairs(object) → {Array}
- Source:
Creates an array of own enumerable key-value pairs for object
which
can be consumed by _.fromPairs
.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.toPairs(new Foo);
// => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
Returns:
Returns the new array of key-value pairs.
- Type
- Array
(static) toPairsIn(object) → {Array}
- Source:
Creates an array of own and inherited enumerable key-value pairs for
object
which can be consumed by _.fromPairs
.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.toPairsIn(new Foo);
// => [['a', 1], ['b', 2], ['c', 1]] (iteration order is not guaranteed)
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
Returns:
Returns the new array of key-value pairs.
- Type
- Array
(static) toPath(value) → {Array}
- Source:
Converts value
to a property path array.
Example
_.toPath('a.b.c');
// => ['a', 'b', 'c']
_.toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']
var path = ['a', 'b', 'c'],
newPath = _.toPath(path);
console.log(newPath);
// => ['a', 'b', 'c']
console.log(path === newPath);
// => false
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to convert. |
Returns:
Returns the new property path array.
- Type
- Array
(static) toPlainObject(value) → {Object}
- Source:
Converts value
to a plain object flattening inherited enumerable
properties of value
to own properties of the plain object.
Example
function Foo() {
this.b = 2;
}
Foo.prototype.c = 3;
_.assign({ 'a': 1 }, new Foo);
// => { 'a': 1, 'b': 2 }
_.assign({ 'a': 1 }, _.toPlainObject(new Foo));
// => { 'a': 1, 'b': 2, 'c': 3 }
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to convert. |
Returns:
Returns the converted plain object.
- Type
- Object
(static) toSafeInteger(value) → {number}
- Source:
Converts value
to a safe integer. A safe integer can be compared and
represented correctly.
Example
_.toSafeInteger(3);
// => 3
_.toSafeInteger(Number.MIN_VALUE);
// => 0
_.toSafeInteger(Infinity);
// => 9007199254740991
_.toSafeInteger('3');
// => 3
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to convert. |
Returns:
Returns the converted integer.
- Type
- number
(static) toString(value) → {string}
- Source:
Converts value
to a string if it's not one. An empty string is returned
for null
and undefined
values. The sign of -0
is preserved.
Example
_.toString(null);
// => ''
_.toString(-0);
// => '-0'
_.toString([1, 2, 3]);
// => '1,2,3'
Parameters:
Name | Type | Description |
---|---|---|
value |
* | The value to process. |
Returns:
Returns the string.
- Type
- string
(static) toUpper(stringopt) → {string}
- Source:
Converts string
, as a whole, to upper case.
Example
_.toUpper('--foo-bar');
// => '--FOO-BAR'
_.toUpper('fooBar');
// => 'FOOBAR'
_.toUpper('__foo_bar__');
// => '__FOO_BAR__'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to convert. |
Returns:
Returns the upper cased string.
- Type
- string
(static) transform(object, iterateeopt, accumulatoropt) → {*}
- Source:
An alternative to _.reduce
; this method transforms object
to a new
accumulator
object which is the result of running each of its own enumerable
properties through iteratee
, with each invocation potentially mutating
the accumulator
object. The iteratee is invoked with four arguments:
(accumulator, value, key, object). Iteratee functions may exit iteration
early by explicitly returning false
.
Example
_.transform([2, 3, 4], function(result, n) {
result.push(n *= n);
return n % 2 == 0;
}, []);
// => [4, 9]
_.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
(result[value] || (result[value] = [])).push(key);
}, {});
// => { '1': ['a', 'c'], '2': ['b'] }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
object |
Array | Object | The object to iterate over. |
||
iteratee |
function |
<optional> |
_.identity | The function invoked per iteration. |
accumulator |
* |
<optional> |
The custom accumulator value. |
Returns:
Returns the accumulated value.
- Type
- *
(static) trim(stringopt, charsopt) → {string}
- Source:
Removes leading and trailing whitespace or specified characters from string
.
Example
_.trim(' abc ');
// => 'abc'
_.trim('-_-abc-_-', '_-');
// => 'abc'
_.map([' foo ', ' bar '], _.trim);
// => ['foo', 'bar']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to trim. |
chars |
string |
<optional> |
whitespace | The characters to trim. |
Returns:
Returns the trimmed string.
- Type
- string
(static) trimEnd(stringopt, charsopt) → {string}
- Source:
Removes trailing whitespace or specified characters from string
.
Example
_.trimEnd(' abc ');
// => ' abc'
_.trimEnd('-_-abc-_-', '_-');
// => '-_-abc'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to trim. |
chars |
string |
<optional> |
whitespace | The characters to trim. |
Returns:
Returns the trimmed string.
- Type
- string
(static) trimStart(stringopt, charsopt) → {string}
- Source:
Removes leading whitespace or specified characters from string
.
Example
_.trimStart(' abc ');
// => 'abc '
_.trimStart('-_-abc-_-', '_-');
// => 'abc-_-'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to trim. |
chars |
string |
<optional> |
whitespace | The characters to trim. |
Returns:
Returns the trimmed string.
- Type
- string
(static) truncate(stringopt, optionsopt) → {string}
- Source:
Truncates string
if it's longer than the given maximum string length.
The last characters of the truncated string are replaced with the omission
string which defaults to "...".
Example
_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'
_.truncate('hi-diddly-ho there, neighborino', {
'length': 24,
'separator': ' '
});
// => 'hi-diddly-ho there,...'
_.truncate('hi-diddly-ho there, neighborino', {
'length': 24,
'separator': /,? +/
});
// => 'hi-diddly-ho there...'
_.truncate('hi-diddly-ho there, neighborino', {
'omission': ' [...]'
});
// => 'hi-diddly-ho there, neig [...]'
Parameters:
Name | Type | Attributes | Default | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
string |
string |
<optional> |
'' | The string to truncate. |
||||||||||||||||||||
options |
Object |
<optional> |
({}) | The options object. Properties
|
Returns:
Returns the truncated string.
- Type
- string
(static) unary(func) → {function}
Creates a function that accepts up to one argument, ignoring any additional arguments.
Example
_.map(['6', '8', '10'], _.unary(parseInt));
// => [6, 8, 10]
Parameters:
Name | Type | Description |
---|---|---|
func |
function | The function to cap arguments for. |
Returns:
Returns the new function.
- Type
- function
(static) unescape(stringopt) → {string}
- Source:
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.
Example
_.unescape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to unescape. |
Returns:
Returns the unescaped string.
- Type
- string
(static) uniq(array) → {Array}
Creates a duplicate-free version of an array, using
SameValueZero
for equality comparisons, in which only the first occurrence of each element
is kept.
Example
_.uniq([2, 1, 2]);
// => [2, 1]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array to inspect. |
Returns:
Returns the new duplicate free array.
- Type
- Array
(static) uniqBy(array, iterateeopt) → {Array}
This method is like _.uniq
except that it accepts iteratee
which is
invoked for each element in array
to generate the criterion by which
uniqueness is computed. The iteratee is invoked with one argument: (value).
Example
_.uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]
// The `_.property` iteratee shorthand.
_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array to inspect. |
||
iteratee |
function | Object | string |
<optional> |
_.identity | The iteratee invoked per element. |
Returns:
Returns the new duplicate free array.
- Type
- Array
(static) uniqueId(prefixopt) → {string}
- Source:
Generates a unique ID. If prefix
is given the ID is appended to it.
Example
_.uniqueId('contact_');
// => 'contact_104'
_.uniqueId();
// => '105'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
prefix |
string |
<optional> |
'' | The value to prefix the ID with. |
Returns:
Returns the unique ID.
- Type
- string
(static) uniqWith(array, comparatoropt) → {Array}
This method is like _.uniq
except that it accepts comparator
which
is invoked to compare elements of array
. The comparator is invoked with
two arguments: (arrVal, othVal).
Example
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
array |
Array | The array to inspect. |
|
comparator |
function |
<optional> |
The comparator invoked per element. |
Returns:
Returns the new duplicate free array.
- Type
- Array
(static) unset(object, path) → {boolean}
- Source:
Removes the property at path
of object
.
Note: This method mutates object
.
Example
var object = { 'a': [{ 'b': { 'c': 7 } }] };
_.unset(object, 'a[0].b.c');
// => true
console.log(object);
// => { 'a': [{ 'b': {} }] };
_.unset(object, 'a[0].b.c');
// => true
console.log(object);
// => { 'a': [{ 'b': {} }] };
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to modify. |
path |
Array | string | The path of the property to unset. |
Returns:
Returns true
if the property is deleted, else false
.
- Type
- boolean
(static) unzip(array) → {Array}
This method is like _.zip
except that it accepts an array of grouped
elements and creates an array regrouping the elements to their pre-zip
configuration.
Example
var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
// => [['fred', 30, true], ['barney', 40, false]]
_.unzip(zipped);
// => [['fred', 'barney'], [30, 40], [true, false]]
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The array of grouped elements to process. |
Returns:
Returns the new array of regrouped elements.
- Type
- Array
(static) unzipWith(array, iterateeopt) → {Array}
This method is like _.unzip
except that it accepts iteratee
to specify
how regrouped values should be combined. The iteratee is invoked with the
elements of each group: (...group).
Example
var zipped = _.zip([1, 2], [10, 20], [100, 200]);
// => [[1, 10, 100], [2, 20, 200]]
_.unzipWith(zipped, _.add);
// => [3, 30, 300]
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
array |
Array | The array of grouped elements to process. |
||
iteratee |
function |
<optional> |
_.identity | The function to combine regrouped values. |
Returns:
Returns the new array of regrouped elements.
- Type
- Array
(static) values(object) → {Array}
- Source:
Creates an array of the own enumerable property values of object
.
Note: Non-object values are coerced to objects.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.values(new Foo);
// => [1, 2] (iteration order is not guaranteed)
_.values('hi');
// => ['h', 'i']
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
Returns:
Returns the array of property values.
- Type
- Array
(static) valuesIn(object) → {Array}
- Source:
Creates an array of the own and inherited enumerable property values of object
.
Note: Non-object values are coerced to objects.
Example
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.valuesIn(new Foo);
// => [1, 2, 3] (iteration order is not guaranteed)
Parameters:
Name | Type | Description |
---|---|---|
object |
Object | The object to query. |
Returns:
Returns the array of property values.
- Type
- Array
(static) words(stringopt, patternopt) → {Array}
- Source:
Splits string
into an array of its words.
Example
_.words('fred, barney, & pebbles');
// => ['fred', 'barney', 'pebbles']
_.words('fred, barney, & pebbles', /[^, ]+/g);
// => ['fred', 'barney', '&', 'pebbles']
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
string |
string |
<optional> |
'' | The string to inspect. |
pattern |
RegExp | string |
<optional> |
The pattern to match words. |
Returns:
Returns the words of string
.
- Type
- Array
(static) wrap(value, wrapperopt) → {function}
Creates a function that provides value
to the wrapper function as its
first argument. Any additional arguments provided to the function are
appended to those provided to the wrapper function. The wrapper is invoked
with the this
binding of the created function.
Example
var p = _.wrap(_.escape, function(func, text) {
return '<p>' + func(text) + '</p>';
});
p('fred, barney, & pebbles');
// => '<p>fred, barney, & pebbles</p>'
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
value |
* | The value to wrap. |
||
wrapper |
function |
<optional> |
identity | The wrapper function. |
Returns:
Returns the new function.
- Type
- function
(static) zipObject(propsopt, valuesopt) → {Object}
This method is like _.fromPairs
except that it accepts two arrays,
one of property names and one of corresponding values.
Example
_.zipObject(['a', 'b'], [1, 2]);
// => { 'a': 1, 'b': 2 }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
props |
Array |
<optional> |
[] | The property names. |
values |
Array |
<optional> |
[] | The property values. |
Returns:
Returns the new object.
- Type
- Object
(static) zipObjectDeep(propsopt, valuesopt) → {Object}
This method is like _.zipObject
except that it supports property paths.
Example
_.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
props |
Array |
<optional> |
[] | The property names. |
values |
Array |
<optional> |
[] | The property values. |
Returns:
Returns the new object.
- Type
- Object