lodash v4.13.1
_.chunk_.compact_.concat_.difference_.differenceBy_.differenceWith_.drop_.dropRight_.dropRightWhile_.dropWhile_.fill_.findIndex_.findLastIndex_.first->head_.flatten_.flattenDeep_.flattenDepth_.fromPairs_.head_.indexOf_.initial_.intersection_.intersectionBy_.intersectionWith_.join_.last_.lastIndexOf_.nth_.pull_.pullAll_.pullAllBy_.pullAllWith_.pullAt_.remove_.reverse_.slice_.sortedIndex_.sortedIndexBy_.sortedIndexOf_.sortedLastIndex_.sortedLastIndexBy_.sortedLastIndexOf_.sortedUniq_.sortedUniqBy_.tail_.take_.takeRight_.takeRightWhile_.takeWhile_.union_.unionBy_.unionWith_.uniq_.uniqBy_.uniqWith_.unzip_.unzipWith_.without_.xor_.xorBy_.xorWith_.zip_.zipObject_.zipObjectDeep_.zipWith
_.countBy_.each->forEach_.eachRight->forEachRight_.every_.filter_.find_.findLast_.flatMap_.flatMapDeep_.flatMapDepth_.forEach_.forEachRight_.groupBy_.includes_.invokeMap_.keyBy_.map_.orderBy_.partition_.reduce_.reduceRight_.reject_.sample_.sampleSize_.shuffle_.size_.some_.sortBy
_.after_.ary_.before_.bind_.bindKey_.curry_.curryRight_.debounce_.defer_.delay_.flip_.memoize_.negate_.once_.overArgs_.partial_.partialRight_.rearg_.rest_.spread_.throttle_.unary_.wrap
_.castArray_.clone_.cloneDeep_.cloneDeepWith_.cloneWith_.eq_.gt_.gte_.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_.isSymbol_.isTypedArray_.isUndefined_.isWeakMap_.isWeakSet_.lt_.lte_.toArray_.toFinite_.toInteger_.toLength_.toNumber_.toPlainObject_.toSafeInteger_.toString
_.add_.ceil_.divide_.floor_.max_.maxBy_.mean_.meanBy_.min_.minBy_.multiply_.round_.subtract_.sum_.sumBy
_.assign_.assignIn_.assignInWith_.assignWith_.at_.create_.defaults_.defaultsDeep_.entries->toPairs_.entriesIn->toPairsIn_.extend->assignIn_.extendWith->assignInWith_.findKey_.findLastKey_.forIn_.forInRight_.forOwn_.forOwnRight_.functions_.functionsIn_.get_.has_.hasIn_.invert_.invertBy_.invoke_.keys_.keysIn_.mapKeys_.mapValues_.merge_.mergeWith_.omit_.omitBy_.pick_.pickBy_.result_.set_.setWith_.toPairs_.toPairsIn_.transform_.unset_.update_.updateWith_.values_.valuesIn
__.chain_.tap_.thru_.prototype[Symbol.iterator]_.prototype.at_.prototype.chain_.prototype.commit_.prototype.next_.prototype.plant_.prototype.reverse_.prototype.toJSON->value_.prototype.value_.prototype.valueOf->value
_.camelCase_.capitalize_.deburr_.endsWith_.escape_.escapeRegExp_.kebabCase_.lowerCase_.lowerFirst_.pad_.padEnd_.padStart_.parseInt_.repeat_.replace_.snakeCase_.split_.startCase_.startsWith_.template_.toLower_.toUpper_.trim_.trimEnd_.trimStart_.truncate_.unescape_.upperCase_.upperFirst_.words
_.attempt_.bindAll_.cond_.conforms_.constant_.flow_.flowRight_.identity_.iteratee_.matches_.matchesProperty_.method_.methodOf_.mixin_.noConflict_.noop_.nthArg_.over_.overEvery_.overSome_.property_.propertyOf_.range_.rangeRight_.runInContext_.stubArray_.stubFalse_.stubObject_.stubString_.stubTrue_.times_.toPath_.uniqueId
_.VERSION_.templateSettings_.templateSettings.escape_.templateSettings.evaluate_.templateSettings.imports_.templateSettings.interpolate_.templateSettings.variable
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.
3.0.0
size(number): The length of each chunkarray(Array): The array to process.
(Array): Returns the new array of chunks.
_.chunk(2, ['a', 'b', 'c', 'd']);
// => [['a', 'b'], ['c', 'd']]
_.chunk(3, ['a', 'b', 'c', 'd']);
// => [['a', 'b', 'c'], ['d']]Creates an array with all falsey values removed. The values false, null,
0, "", undefined, and NaN are falsey.
0.1.0
array(Array): The array to compact.
(Array): Returns the new array of filtered values.
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]Creates a new array concatenating array with any additional arrays
and/or values.
4.0.0
array(Array): The array to concatenate.values(*|*[]): The values to concatenate.
(Array): Returns the new concatenated array.
var array = [1];
var other = _.concat(array, [2, [3], [[4]]]);
// => [1, 2, 3, [4]]
// => [1]Creates an array of unique array values not included in the other given
arrays using SameValueZero
for equality comparisons. The order of result values is determined by the
order they occur in the first array.
0.1.0
array(Array): The array to inspect.values(Array|Array[]): The values to exclude.
(Array): Returns the new array of filtered values.
_.difference([2, 1], [2, 3]);
// => [1]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 they're compared. Result values are chosen from the first array.
The iteratee is invoked with one argument: (value).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.array(Array): The array to inspect.values(Array|Array[]): The values to exclude.
(Array): Returns the new array of filtered values.
_.differenceBy(Math.floor, [2.1, 1.2], [2.3, 3.4]);
// => [1.2]
// The `_.property` iteratee shorthand.
_.differenceBy('x', [{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }]);
// => [{ 'x': 2 }]This method is like _.difference except that it accepts comparator
which is invoked to compare elements of array to values. Result values
are chosen from the first array. The comparator is invoked with two arguments:
(arrVal, othVal).
4.0.0
comparator(Function): The comparator invoked per element.array(Array): The array to inspect.values(Array|Array[]): The values to exclude.
(Array): Returns the new array of filtered values.
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
_.differenceWith(_.isEqual, objects, [{ 'x': 1, 'y': 2 }]);
// => [{ 'x': 2, 'y': 1 }]Creates a slice of array with n elements dropped from the beginning.
0.5.0
n(number): The number of elements to drop.array(Array): The array to query.
(Array): Returns the slice of array.
_.drop(1, [1, 2, 3]);
// => [2, 3]
_.drop(2, [1, 2, 3]);
// => [3]
_.drop(5, [1, 2, 3]);
// => []
_.drop(0, [1, 2, 3]);
// => [1, 2, 3]Creates a slice of array with n elements dropped from the end.
3.0.0
n(number): The number of elements to drop.array(Array): The array to query.
(Array): Returns the slice of array.
_.dropRight(1, [1, 2, 3]);
// => [1, 2]
_.dropRight(2, [1, 2, 3]);
// => [1]
_.dropRight(5, [1, 2, 3]);
// => []
_.dropRight(0, [1, 2, 3]);
// => [1, 2, 3]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).
3.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.array(Array): The array to query.
(Array): Returns the slice of array.
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': false }
];
_.dropRightWhile(function(o) { return !o.active; }, users);
// => objects for ['barney']
// The `_.matches` iteratee shorthand.
_.dropRightWhile({ 'user': 'pebbles', 'active': false }, users);
// => objects for ['barney', 'fred']
// The `_.matchesProperty` iteratee shorthand.
_.dropRightWhile(['active', false], users);
// => objects for ['barney']
// The `_.property` iteratee shorthand.
_.dropRightWhile('active', users);
// => objects for ['barney', 'fred', 'pebbles']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).
3.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.array(Array): The array to query.
(Array): Returns the slice of array.
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.dropWhile(function(o) { return !o.active; }, users);
// => objects for ['pebbles']
// The `_.matches` iteratee shorthand.
_.dropWhile({ 'user': 'barney', 'active': false }, users);
// => objects for ['fred', 'pebbles']
// The `_.matchesProperty` iteratee shorthand.
_.dropWhile(['active', false], users);
// => objects for ['pebbles']
// The `_.property` iteratee shorthand.
_.dropWhile('active', users);
// => objects for ['barney', 'fred', 'pebbles']Fills elements of array with value from start up to, but not
including, end.
3.2.0
start(number): The start position.end(number): The end position.value(*): The value to fillarraywith.array(Array): The array to fill.
(Array): Returns array.
var array = [1, 2, 3];
_.fill(0, array.length, 'a', array);
// => ['a', 'a', 'a']
_.fill(0, 3, 2, Array(3));
// => [2, 2, 2]
_.fill(1, 3, '*', [4, 6, 8, 10]);
// => [4, '*', '*', 10]This method is like _.find except that it returns the index of the first
element predicate returns truthy for instead of the element itself.
1.1.0
predicate(Array|Function|Object|string): The function invoked per iteration.array(Array): The array to search.
(number): Returns the index of the found element, else -1.
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.findIndex(function(o) { return o.user == 'barney'; }, users);
// => 0
// The `_.matches` iteratee shorthand.
_.findIndex({ 'user': 'fred', 'active': false }, users);
// => 1
// The `_.matchesProperty` iteratee shorthand.
_.findIndex(['active', false], users);
// => 0
// The `_.property` iteratee shorthand.
_.findIndex('active', users);
// => 2This method is like _.findIndex except that it iterates over elements
of collection from right to left.
2.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.array(Array): The array to search.
(number): Returns the index of the found element, else -1.
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': false }
];
_.findLastIndex(function(o) { return o.user == 'pebbles'; }, users);
// => 2
// The `_.matches` iteratee shorthand.
_.findLastIndex({ 'user': 'barney', 'active': true }, users);
// => 0
// The `_.matchesProperty` iteratee shorthand.
_.findLastIndex(['active', false], users);
// => 2
// The `_.property` iteratee shorthand.
_.findLastIndex('active', users);
// => 0Flattens array a single level deep.
0.1.0
array(Array): The array to flatten.
(Array): Returns the new flattened array.
_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]Recursively flattens array.
3.0.0
array(Array): The array to flatten.
(Array): Returns the new flattened array.
_.flattenDeep([1, [2, [3, [4]], 5]]);
// => [1, 2, 3, 4, 5]Recursively flatten array up to depth times.
4.4.0
depth(number): The maximum recursion depth.array(Array): The array to flatten.
(Array): Returns the new flattened array.
var array = [1, [2, [3, [4]], 5]];
_.flattenDepth(1, array);
// => [1, 2, [3, [4]], 5]
_.flattenDepth(2, array);
// => [1, 2, 3, [4], 5]The inverse of _.toPairs; this method returns an object composed
from key-value pairs.
4.0.0
pairs(Array): The key-value pairs.
(Object): Returns the new object.
_.fromPairs([['fred', 30], ['barney', 40]]);
// => { 'fred': 30, 'barney': 40 }Gets the first element of array.
0.1.0
_.first
array(Array): The array to query.
(*): Returns the first element of array.
_.head([1, 2, 3]);
// => 1
_.head([]);
// => undefinedGets 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.
0.1.0
value(*): The value to search for.array(Array): The array to search.
(number): Returns the index of the matched value, else -1.
_.indexOf(2, [1, 2, 1, 2]);
// => 1
// Search from the `fromIndex`.
_.indexOf([2, 2], [1, 2, 1, 2]);
// => 3Gets all but the last element of array.
0.1.0
array(Array): The array to query.
(Array): Returns the slice of array.
_.initial([1, 2, 3]);
// => [1, 2]Creates an array of unique values that are included in all given arrays
using SameValueZero
for equality comparisons. The order of result values is determined by the
order they occur in the first array.
0.1.0
arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of intersecting values.
_.intersection([2, 3], [2, 1]);
// => [2]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 they're compared. Result values are chosen from the first array.
The iteratee is invoked with one argument: (value).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of intersecting values.
_.intersectionBy(Math.floor, [2.1, 1.2], [2.3, 3.4]);
// => [2.1]
// The `_.property` iteratee shorthand.
_.intersectionBy('x', [{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }]);
// => [{ 'x': 1 }]This method is like _.intersection except that it accepts comparator
which is invoked to compare elements of arrays. Result values are chosen
from the first array. The comparator is invoked with two arguments:
(arrVal, othVal).
4.0.0
comparator(Function): The comparator invoked per element.arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of intersecting values.
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.intersectionWith(_.isEqual, objects, others);
// => [{ 'x': 1, 'y': 2 }]Converts all elements in array into a string separated by separator.
4.0.0
separator(string): The element separator.array(Array): The array to convert.
(string): Returns the joined string.
_.join('~', ['a', 'b', 'c']);
// => 'a~b~c'Gets the last element of array.
0.1.0
array(Array): The array to query.
(*): Returns the last element of array.
_.last([1, 2, 3]);
// => 3This method is like _.indexOf except that it iterates over elements of
array from right to left.
0.1.0
value(*): The value to search for.array(Array): The array to search.
(number): Returns the index of the matched value, else -1.
_.lastIndexOf(2, [1, 2, 1, 2]);
// => 3
// Search from the `fromIndex`.
_.lastIndexOf([2, 2], [1, 2, 1, 2]);
// => 1Gets the element at index n of array. If n is negative, the nth
element from the end is returned.
4.11.0
n(number): The index of the element to return.array(Array): The array to query.
(*): Returns the nth element of array.
var array = ['a', 'b', 'c', 'd'];
_.nth(1, array);
// => 'b'
_.nth(-2, array);
// => 'c';Removes all given values from array using
SameValueZero
for equality comparisons.
2.0.0
values(*|*[]): The values to remove.array(Array): The array to modify.
(Array): Returns array.
var array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pull(['a', 'c'], array);
// => ['b', 'b']This method is like _.pull except that it accepts an array of values to remove.
4.0.0
values(Array): The values to remove.array(Array): The array to modify.
(Array): Returns array.
var array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pullAll(['a', 'c'], array);
// => ['b', 'b']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 they're compared. The iteratee is invoked with one argument: (value).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.values(Array): The values to remove.array(Array): The array to modify.
(Array): Returns array.
var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
_.pullAllBy('x', [{ 'x': 1 }, { 'x': 3 }], array);
// => [{ 'x': 2 }]This method is like _.pullAll except that it accepts comparator which
is invoked to compare elements of array to values. The comparator is
invoked with two arguments: (arrVal, othVal).
4.6.0
comparator(Function): The comparator invoked per element.values(Array): The values to remove.array(Array): The array to modify.
(Array): Returns array.
var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
_.pullAllWith(_.isEqual, [{ 'x': 3, 'y': 4 }], array);
// => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]Removes elements from array corresponding to indexes and returns an
array of removed elements.
3.0.0
indexes(number|number[]): The indexes of elements to remove.array(Array): The array to modify.
(Array): Returns the new array of removed elements.
var array = ['a', 'b', 'c', 'd'];
var pulled = _.pullAt([1, 3], array);
// => ['a', 'c']
// => ['b', 'd']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).
2.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.array(Array): The array to modify.
(Array): Returns the new array of removed elements.
var array = [1, 2, 3, 4];
var evens = _.remove(function(n) {
return n % 2 == 0;
}, array);
// => [1, 3]
// => [2, 4]Reverses array so that the first element becomes the last, the second
element becomes the second to last, and so on.
4.0.0
array(Array): The array to modify.
(Array): Returns array.
var array = [1, 2, 3];
_.reverse(array);
// => [3, 2, 1]
// => [3, 2, 1]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.
3.0.0
start(number): The start position.end(number): The end position.array(Array): The array to slice.
(Array): Returns the slice of array.
Uses a binary search to determine the lowest index at which value
should be inserted into array in order to maintain its sort order.
0.1.0
value(*): The value to evaluate.array(Array): The sorted array to inspect.
(number): Returns the index at which value should be inserted into array.
_.sortedIndex(40, [30, 50]);
// => 1This 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).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.value(*): The value to evaluate.array(Array): The sorted array to inspect.
(number): Returns the index at which value should be inserted into array.
var objects = [{ 'x': 4 }, { 'x': 5 }];
_.sortedIndexBy(function(o) { return o.x; }, { 'x': 4 }, objects);
// => 0
// The `_.property` iteratee shorthand.
_.sortedIndexBy('x', { 'x': 4 }, objects);
// => 0This method is like _.indexOf except that it performs a binary
search on a sorted array.
4.0.0
value(*): The value to search for.array(Array): The array to search.
(number): Returns the index of the matched value, else -1.
_.sortedIndexOf(5, [4, 5, 5, 5, 6]);
// => 1This 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.
3.0.0
value(*): The value to evaluate.array(Array): The sorted array to inspect.
(number): Returns the index at which value should be inserted into array.
_.sortedLastIndex(5, [4, 5, 5, 5, 6]);
// => 4This 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).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.value(*): The value to evaluate.array(Array): The sorted array to inspect.
(number): Returns the index at which value should be inserted into array.
var objects = [{ 'x': 4 }, { 'x': 5 }];
_.sortedLastIndexBy(function(o) { return o.x; }, { 'x': 4 }, objects);
// => 1
// The `_.property` iteratee shorthand.
_.sortedLastIndexBy('x', { 'x': 4 }, objects);
// => 1This method is like _.lastIndexOf except that it performs a binary
search on a sorted array.
4.0.0
value(*): The value to search for.array(Array): The array to search.
(number): Returns the index of the matched value, else -1.
_.sortedLastIndexOf(5, [4, 5, 5, 5, 6]);
// => 3This method is like _.uniq except that it's designed and optimized
for sorted arrays.
4.0.0
array(Array): The array to inspect.
(Array): Returns the new duplicate free array.
_.sortedUniq([1, 1, 2]);
// => [1, 2]This method is like _.uniqBy except that it's designed and optimized
for sorted arrays.
4.0.0
iteratee(Function): The iteratee invoked per element.array(Array): The array to inspect.
(Array): Returns the new duplicate free array.
_.sortedUniqBy(Math.floor, [1.1, 1.2, 2.3, 2.4]);
// => [1.1, 2.3]Gets all but the first element of array.
4.0.0
array(Array): The array to query.
(Array): Returns the slice of array.
_.tail([1, 2, 3]);
// => [2, 3]Creates a slice of array with n elements taken from the beginning.
0.1.0
n(number): The number of elements to take.array(Array): The array to query.
(Array): Returns the slice of array.
_.take(1, [1, 2, 3]);
// => [1]
_.take(2, [1, 2, 3]);
// => [1, 2]
_.take(5, [1, 2, 3]);
// => [1, 2, 3]
_.take(0, [1, 2, 3]);
// => []Creates a slice of array with n elements taken from the end.
3.0.0
n(number): The number of elements to take.array(Array): The array to query.
(Array): Returns the slice of array.
_.takeRight(1, [1, 2, 3]);
// => [3]
_.takeRight(2, [1, 2, 3]);
// => [2, 3]
_.takeRight(5, [1, 2, 3]);
// => [1, 2, 3]
_.takeRight(0, [1, 2, 3]);
// => []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).
3.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.array(Array): The array to query.
(Array): Returns the slice of array.
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': false }
];
_.takeRightWhile(function(o) { return !o.active; }, users);
// => objects for ['fred', 'pebbles']
// The `_.matches` iteratee shorthand.
_.takeRightWhile({ 'user': 'pebbles', 'active': false }, users);
// => objects for ['pebbles']
// The `_.matchesProperty` iteratee shorthand.
_.takeRightWhile(['active', false], users);
// => objects for ['fred', 'pebbles']
// The `_.property` iteratee shorthand.
_.takeRightWhile('active', users);
// => []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).
3.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.array(Array): The array to query.
(Array): Returns the slice of array.
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false},
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(function(o) { return !o.active; }, users);
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile({ 'user': 'barney', 'active': false }, users);
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(['active', false], users);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile('active', users);
// => []Creates an array of unique values, in order, from all given arrays using
SameValueZero
for equality comparisons.
0.1.0
arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of combined values.
_.union([1, 2], [2]);
// => [2, 1]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).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of combined values.
_.unionBy(Math.floor, [2.1], [1.2, 2.3]);
// => [2.1, 1.2]
// The `_.property` iteratee shorthand.
_.unionBy('x', [{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }]);
// => [{ 'x': 1 }, { 'x': 2 }]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).
4.0.0
comparator(Function): The comparator invoked per element.arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of combined values.
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.unionWith(_.isEqual, objects, others);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]Creates a duplicate-free version of an array, using
SameValueZero
for equality comparisons, in which only the first occurrence of each
element is kept.
0.1.0
array(Array): The array to inspect.
(Array): Returns the new duplicate free array.
_.uniq([2, 1, 2]);
// => [2, 1]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).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.array(Array): The array to inspect.
(Array): Returns the new duplicate free array.
_.uniqBy(Math.floor, [2.1, 1.2, 2.3]);
// => [2.1, 1.2]
// The `_.property` iteratee shorthand.
_.uniqBy('x', [{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }]);
// => [{ 'x': 1 }, { 'x': 2 }]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).
4.0.0
comparator(Function): The comparator invoked per element.array(Array): The array to inspect.
(Array): Returns the new duplicate free array.
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(_.isEqual, objects);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]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.
1.2.0
array(Array): The array of grouped elements to process.
(Array): Returns the new array of regrouped elements.
var zipped = _.zip(['fred', 'barney'], [[30, 40], [true, false]]);
// => [['fred', 30, true], ['barney', 40, false]]
_.unzip(zipped);
// => [['fred', 'barney'], [30, 40], [true, false]]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).
3.8.0
iteratee(Function): The function to combine regrouped values.array(Array): The array of grouped elements to process.
(Array): Returns the new array of regrouped elements.
var zipped = _.zip([1, 2], [[10, 20], [100, 200]]);
// => [[1, 10, 100], [2, 20, 200]]
_.unzipWith(_.add, zipped);
// => [3, 30, 300]Creates an array excluding all given values using
SameValueZero
for equality comparisons.
0.1.0
values(*|*[]): The values to exclude.array(Array): The array to inspect.
(Array): Returns the new array of filtered values.
_.without([1, 2], [2, 1, 2, 3]);
// => [3]Creates an array of unique values that is the symmetric difference of the given arrays. The order of result values is determined by the order they occur in the arrays.
2.4.0
arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of filtered values.
_.xor([2, 3], [2, 1]);
// => [1, 3]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 by which they're compared. The iteratee is invoked with one argument:
(value).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of filtered values.
_.xorBy(Math.floor, [2.1, 1.2], [2.3, 3.4]);
// => [1.2, 3.4]
// The `_.property` iteratee shorthand.
_.xorBy('x', [{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }]);
// => [{ 'x': 2 }]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).
4.0.0
comparator(Function): The comparator invoked per element.arrays(Array): The arrays to inspect.arrays(Array): The arrays to inspect.
(Array): Returns the new array of filtered values.
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.xorWith(_.isEqual, objects, others);
// => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]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.
0.1.0
arrays(Array): The arrays to process.arrays(Array): The arrays to process.
(Array): Returns the new array of grouped elements.
_.zip(['fred', 'barney'], [[30, 40], [true, false]]);
// => [['fred', 30, true], ['barney', 40, false]]This method is like _.fromPairs except that it accepts two arrays,
one of property identifiers and one of corresponding values.
0.4.0
props(Array): The property identifiers.values(Array): The property values.
(Object): Returns the new object.
_.zipObject(['a', 'b'], [1, 2]);
// => { 'a': 1, 'b': 2 }This method is like _.zipObject except that it supports property paths.
4.1.0
values(Array): The property values.props(Array): The property identifiers.
(Object): Returns the new object.
_.zipObjectDeep([1, 2], ['a.b[0].c', 'a.b[1].d']);
// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }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).
3.8.0
iteratee(Function): The function to combine grouped values.arrays(Array): The arrays to process.arrays(Array): The arrays to process.
(Array): Returns the new array of grouped elements.
_.zipWith([[100, 200], function(a, b, c) {
return a + b + c;
}], [1, 2], [10, 20]);
// => [111, 222]Creates an object composed of keys generated from the results of running
each element of collection thru 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).
0.5.0
iteratee(Array|Function|Object|string): The iteratee to transform keys.collection(Array|Object): The collection to iterate over.
(Object): Returns the composed aggregate object.
_.countBy(Math.floor, [6.1, 4.2, 6.3]);
// => { '4': 1, '6': 2 }
// The `_.property` iteratee shorthand.
_.countBy('length', ['one', 'two', 'three']);
// => { '3': 2, '5': 1 }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).
0.1.0
predicate(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(boolean): Returns true if all elements pass the predicate check, else false.
_.every(Boolean, [true, 1, null, 'yes']);
// => false
var users = [
{ 'user': 'barney', 'age': 36, 'active': false },
{ 'user': 'fred', 'age': 40, 'active': false }
];
// The `_.matches` iteratee shorthand.
_.every({ 'user': 'barney', 'active': false }, users);
// => false
// The `_.matchesProperty` iteratee shorthand.
_.every(['active', false], users);
// => true
// The `_.property` iteratee shorthand.
_.every('active', users);
// => falseIterates 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).
0.1.0
predicate(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(Array): Returns the new filtered array.
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(function(o) { return !o.active; }, users);
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.filter({ 'age': 36, 'active': true }, users);
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.filter(['active', false], users);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.filter('active', users);
// => objects for ['barney']Iterates over elements of collection, returning the first element
predicate returns truthy for. The predicate is invoked with three
arguments: (value, index|key, collection).
0.1.0
predicate(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to search.
(*): Returns the matched element, else undefined.
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
];
_.find(function(o) { return o.age < 40; }, users);
// => object for 'barney'
// The `_.matches` iteratee shorthand.
_.find({ 'age': 1, 'active': true }, users);
// => object for 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.find(['active', false], users);
// => object for 'fred'
// The `_.property` iteratee shorthand.
_.find('active', users);
// => object for 'barney'This method is like _.find except that it iterates over elements of
collection from right to left.
2.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to search.
(*): Returns the matched element, else undefined.
_.findLast(function(n) {
return n % 2 == 1;
}, [1, 2, 3, 4]);
// => 3Creates a flattened array of values by running each element in collection
thru iteratee and flattening the mapped results. The iteratee is invoked
with three arguments: (value, index|key, collection).
4.0.0
iteratee(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(Array): Returns the new flattened array.
function duplicate(n) {
return [n, n];
}
_.flatMap(duplicate, [1, 2]);
// => [1, 1, 2, 2]This method is like _.flatMap except that it recursively flattens the
mapped results.
4.7.0
iteratee(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(Array): Returns the new flattened array.
function duplicate(n) {
return [[[n, n]]];
}
_.flatMapDeep(duplicate, [1, 2]);
// => [1, 1, 2, 2]This method is like _.flatMap except that it recursively flattens the
mapped results up to depth times.
4.7.0
iteratee(Array|Function|Object|string): The function invoked per iteration.depth(number): The maximum recursion depth.collection(Array|Object): The collection to iterate over.
(Array): Returns the new flattened array.
function duplicate(n) {
return [[[n, n]]];
}
_.flatMapDepth(duplicate, 2, [1, 2]);
// => [[1, 1], [2, 2]]Iterates over elements of collection and invokes 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.
0.1.0
_.each
iteratee(Function): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(*): Returns collection.
_([1, 2]).forEach(function(value) {
console.log(value);
});
// => Logs `1` then `2`.
_.forEach(function(value, key) {
console.log(key);
}, { 'a': 1, 'b': 2 });
// => Logs 'a' then 'b' (iteration order is not guaranteed).This method is like _.forEach except that it iterates over elements of
collection from right to left.
2.0.0
_.eachRight
iteratee(Function): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(*): Returns collection.
_.forEachRight(function(value) {
console.log(value);
}, [1, 2]);
// => Logs `2` then `1`.Creates an object composed of keys generated from the results of running
each element of collection thru iteratee. The order of grouped values
is determined by the order they occur in collection. The corresponding
value of each key is an array of elements responsible for generating the
key. The iteratee is invoked with one argument: (value).
0.1.0
iteratee(Array|Function|Object|string): The iteratee to transform keys.collection(Array|Object): The collection to iterate over.
(Object): Returns the composed aggregate object.
_.groupBy(Math.floor, [6.1, 4.2, 6.3]);
// => { '4': [4.2], '6': [6.1, 6.3] }
// The `_.property` iteratee shorthand.
_.groupBy('length', ['one', 'two', 'three']);
// => { '3': ['one', 'two'], '5': ['three'] }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.
0.1.0
value(*): The value to search for.collection(Array|Object|string): The collection to search.
(boolean): Returns true if value is found, else false.
_.includes(1, [1, 2, 3]);
// => true
_.includes([1, 2], [1, 2, 3]);
// => false
_.includes('fred', { 'user': 'fred', 'age': 40 });
// => true
_.includes('eb', 'pebbles');
// => trueInvokes 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.
4.0.0
path(Array|Function|string): The path of the method to invoke or the function invoked per iteration.collection(Array|Object): The collection to iterate over.
(Array): Returns the array of results.
_.invokeMap('sort', [[5, 1, 7], [3, 2, 1]]);
// => [[1, 5, 7], [1, 2, 3]]
_.invokeMap([String.prototype.split, ''], [123, 456]);
// => [['1', '2', '3'], ['4', '5', '6']]Creates an object composed of keys generated from the results of running
each element of collection thru iteratee. The corresponding value of
each key is the last element responsible for generating the key. The
iteratee is invoked with one argument: (value).
4.0.0
iteratee(Array|Function|Object|string): The iteratee to transform keys.collection(Array|Object): The collection to iterate over.
(Object): Returns the composed aggregate object.
var array = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
_.keyBy(function(o) {
return String.fromCharCode(o.code);
}, array);
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
_.keyBy('dir', array);
// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }Creates an array of values by running each element in collection thru
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, chunk, curry, curryRight, drop, dropRight, every,
fill, invert, parseInt, random, range, rangeRight, repeat,
sampleSize, slice, some, sortBy, split, take, takeRight,
template, trim, trimEnd, trimStart, and words
0.1.0
iteratee(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(Array): Returns the new mapped array.
function square(n) {
return n * n;
}
_.map(square, [4, 8]);
// => [16, 64]
_.map(square, { 'a': 4, 'b': 8 });
// => [16, 64] (iteration order is not guaranteed)
var users = [
{ 'user': 'barney' },
{ 'user': 'fred' }
];
// The `_.property` iteratee shorthand.
_.map('user', users);
// => ['barney', 'fred']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.
4.0.0
iteratees(Array[]|Function[]|Object[]|string[]): The iteratees to sort by.orders(string[]): The sort orders ofiteratees.collection(Array|Object): The collection to iterate over.
(Array): Returns the new sorted array.
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 34 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 36 }
];
// Sort by `user` in ascending order and by `age` in descending order.
_.orderBy(['user', 'age'], ['asc', 'desc'], users);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]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).
3.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(Array): Returns the array of grouped elements.
var users = [
{ 'user': 'barney', 'age': 36, 'active': false },
{ 'user': 'fred', 'age': 40, 'active': true },
{ 'user': 'pebbles', 'age': 1, 'active': false }
];
_.partition(function(o) { return o.active; }, users);
// => objects for [['fred'], ['barney', 'pebbles']]
// The `_.matches` iteratee shorthand.
_.partition({ 'age': 1, 'active': false }, users);
// => objects for [['pebbles'], ['barney', 'fred']]
// The `_.matchesProperty` iteratee shorthand.
_.partition(['active', false], users);
// => objects for [['barney', 'pebbles'], ['fred']]
// The `_.property` iteratee shorthand.
_.partition('active', users);
// => objects for [['fred'], ['barney', 'pebbles']]Reduces collection to a value which is the accumulated result of running
each element in collection thru 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
0.1.0
iteratee(Function): The function invoked per iteration.accumulator(*): The initial value.collection(Array|Object): The collection to iterate over.
(*): Returns the accumulated value.
_.reduce(function(sum, n) {
return sum + n;
}, 0, [1, 2]);
// => 3
_.reduce(function(result, value, key) {
(result[value] || (result[value] = [])).push(key);
return result;
}, {}, { 'a': 1, 'b': 2, 'c': 1 });
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)This method is like _.reduce except that it iterates over elements of
collection from right to left.
0.1.0
iteratee(Function): The function invoked per iteration.accumulator(*): The initial value.collection(Array|Object): The collection to iterate over.
(*): Returns the accumulated value.
var array = [[0, 1], [2, 3], [4, 5]];
_.reduceRight(function(flattened, other) {
return flattened.concat(other);
}, [], array);
// => [4, 5, 2, 3, 0, 1]The opposite of _.filter; this method returns the elements of collection
that predicate does not return truthy for.
0.1.0
predicate(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(Array): Returns the new filtered array.
var users = [
{ 'user': 'barney', 'age': 36, 'active': false },
{ 'user': 'fred', 'age': 40, 'active': true }
];
_.reject(function(o) { return !o.active; }, users);
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.reject({ 'age': 40, 'active': true }, users);
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.reject(['active', false], users);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.reject('active', users);
// => objects for ['barney']Gets a random element from collection.
2.0.0
collection(Array|Object): The collection to sample.
(*): Returns the random element.
_.sample([1, 2, 3, 4]);
// => 2Gets n random elements at unique keys from collection up to the
size of collection.
4.0.0
n(number): The number of elements to sample.collection(Array|Object): The collection to sample.
(Array): Returns the random elements.
_.sampleSize(2, [1, 2, 3]);
// => [3, 1]
_.sampleSize(4, [1, 2, 3]);
// => [2, 3, 1]Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.
0.1.0
collection(Array|Object): The collection to shuffle.
(Array): Returns the new shuffled array.
_.shuffle([1, 2, 3, 4]);
// => [4, 1, 3, 2]Gets the size of collection by returning its length for array-like
values or the number of own enumerable string keyed properties for objects.
0.1.0
collection(Array|Object): The collection to inspect.
(number): Returns the collection size.
_.size([1, 2, 3]);
// => 3
_.size({ 'a': 1, 'b': 2 });
// => 2
_.size('pebbles');
// => 7Checks 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).
0.1.0
predicate(Array|Function|Object|string): The function invoked per iteration.collection(Array|Object): The collection to iterate over.
(boolean): Returns true if any element passes the predicate check, else false.
_.some(Boolean, [null, 0, 'yes', false]);
// => true
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false }
];
// The `_.matches` iteratee shorthand.
_.some({ 'user': 'barney', 'active': false }, users);
// => false
// The `_.matchesProperty` iteratee shorthand.
_.some(['active', false], users);
// => true
// The `_.property` iteratee shorthand.
_.some('active', users);
// => trueCreates an array of elements, sorted in ascending order by the results of running each element in a collection thru 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).
0.1.0
iteratees(Array|Function|Object|string)|(Array|Function|Object|string)[]): The iteratees to sort by.collection(Array|Object): The collection to iterate over.
(Array): Returns the new sorted array.
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
_.sortBy(function(o) { return o.user; }, users);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
_.sortBy(['user', 'age'], users);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
_.sortBy(['user', function(o) {
return Math.floor(o.age / 10);
}], users);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]Gets the timestamp of the number of milliseconds that have elapsed since
the Unix epoch (1 January 1970 00:00:00 UTC).
2.4.0
(number): Returns the timestamp.
_.defer([function(stamp) {
console.log(_.now(null) - stamp);
}, _.now()]);
// => Logs the number of milliseconds it took for the deferred invocation.The opposite of _.before; this method creates a function that invokes
func once it's called n or more times.
0.1.0
func(Function): The function to restrict.n(number): The number of calls beforefuncis invoked.
(Function): Returns the new restricted function.
var saves = ['profile', 'settings'];
var done = _.after(function() {
console.log('done saving!');
}, saves.length);
_.forEach(function(type) {
asyncSave({ 'type': type, 'complete': done });
}, saves);
// => Logs 'done saving!' after the two async saves have completed.Creates a function that invokes func, with up to n arguments,
ignoring any additional arguments.
3.0.0
n(number): The arity cap.func(Function): The function to cap arguments for.
(Function): Returns the new capped function.
_.map(_.ary(parseInt, 1), ['6', '8', '10']);
// => [6, 8, 10]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.
3.0.0
func(Function): The function to restrict.n(number): The number of calls at whichfuncis no longer invoked.
(Function): Returns the new restricted function.
jQuery(element).on('click', _.before(addContactToList, 5));
// => allows adding up to 4 contacts to the listCreates a function that invokes func with the this binding of thisArg
and partials prepended to the arguments it receives.
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.
0.1.0
func(Function): The function to bind.thisArg(*): Thethisbinding offunc.
(Function): Returns the new bound function.
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!'Creates a function that invokes the method at object[key] with partials
prepended to the arguments it receives.
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.
0.10.0
object(Object): The object to invoke the method on.key(string): The key of the method.
(Function): Returns the new bound function.
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!'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.
2.0.0
func(Function): The function to curry.
(Function): Returns the new curried function.
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]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.
3.0.0
func(Function): The function to curry.
(Function): Returns the new curried function.
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]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.
0.1.0
wait(number): The number of milliseconds to delay.func(Function): The function to debounce.
(Function): Returns the new debounced function.
// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', _.debounce(150, calculateLayout));
// Invoke `sendMail` when clicked, debouncing subsequent calls.
jQuery(element).on('click', _.debounce([300, {
'leading': true,
'trailing': false
}], sendMail));
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = _.debounce([250, { 'maxWait': 1000 }], batchLog);
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// Cancel the trailing debounced invocation.
jQuery(window).on('popstate', debounced.cancel);Defers invoking the func until the current call stack has cleared. Any
additional arguments are provided to func when it's invoked.
0.1.0
func(Function): The function to defer.
(number): Returns the timer id.
_.defer([function(text) {
console.log(text);
}, 'deferred']);
// => Logs 'deferred' after one or more milliseconds.Invokes func after wait milliseconds. Any additional arguments are
provided to func when it's invoked.
0.1.0
wait(number): The number of milliseconds to delay invocation.func(Function): The function to delay.
(number): Returns the timer id.
_.delay([1000, 'later'], function(text) {
console.log(text);
});
// => Logs 'later' after one second.Creates a function that invokes func with arguments reversed.
4.0.0
func(Function): The function to flip arguments for.
(Function): Returns the new flipped function.
var flipped = _.flip(function() {
return _.toArray(arguments);
});
flipped('a', 'b', 'c', 'd');
// => ['d', 'c', 'b', 'a']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.
0.1.0
func(Function): The function to have its output memoized.
(Function): Returns the new memoized function.
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;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.
3.0.0
predicate(Function): The predicate to negate.
(Function): Returns the new negated function.
function isEven(n) {
return n % 2 == 0;
}
_.filter(_.negate(isEven), [1, 2, 3, 4, 5, 6]);
// => [1, 3, 5]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.
0.1.0
func(Function): The function to restrict.
(Function): Returns the new restricted function.
var initialize = _.once(createApplication);
initialize();
initialize();
// `initialize` invokes `createApplication` onceCreates a function that invokes func with arguments transformed by
corresponding transforms.
4.0.0
func(Function): The function to wrap.
(Function): Returns the new function.
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]Creates a function that invokes func with partials prepended to the
arguments it receives. 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.
0.2.0
func(Function): The function to partially apply arguments to.partials(*|*[]): The arguments to be partially applied.
(Function): Returns the new partially applied function.
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'This method is like _.partial except that partially applied arguments
are appended to the arguments it receives.
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.
1.0.0
func(Function): The function to partially apply arguments to.partials(*|*[]): The arguments to be partially applied.
(Function): Returns the new partially applied function.
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'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.
3.0.0
indexes(number|number[]): The arranged argument indexes.func(Function): The function to rearrange arguments for.
(Function): Returns the new function.
var rearged = _.rearg([2, 0, 1], function(a, b, c) {
return [a, b, c];
});
rearged('b', 'c', 'a')
// => ['a', 'b', 'c']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.
4.0.0
func(Function): The function to apply a rest parameter to.
(Function): Returns the new function.
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'Creates a function that invokes func with the this binding of the
create function and an array of arguments much like
Function#apply.
Note: This method is based on the
spread operator.
3.2.0
func(Function): The function to spread arguments over.
(Function): Returns the new function.
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 76Creates 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.
0.1.0
wait(number): The number of milliseconds to throttle invocations to.func(Function): The function to throttle.
(Function): Returns the new throttled function.
// Avoid excessively updating the position while scrolling.
jQuery(window).on('scroll', _.throttle(100, updatePosition));
// Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
var throttled = _.throttle([300000, { 'trailing': false }], renewToken);
jQuery(element).on('click', throttled);
// Cancel the trailing throttled invocation.
jQuery(window).on('popstate', throttled.cancel);Creates a function that accepts up to one argument, ignoring any additional arguments.
4.0.0
func(Function): The function to cap arguments for.
(Function): Returns the new capped function.
_.map(_.unary(parseInt), ['6', '8', '10']);
// => [6, 8, 10]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.
0.1.0
wrapper(Function): The wrapper function.value(*): The value to wrap.
(Function): Returns the new function.
var p = _.wrap(function(func, text) {
return '<p>' + func(text) + '</p>';
}, _.escape);
p('fred, barney, & pebbles');
// => '<p>fred, barney, & pebbles</p>'Casts value as an array if it's not one.
4.4.0
value(*): The value to inspect.
(Array): Returns the cast array.
_.castArray(1);
// => [1]
_.castArray({ 'a': 1 });
// => [{ 'a': 1 }]
_.castArray('abc');
// => ['abc']
_.castArray(null);
// => [null]
_.castArray(undefined);
// => [undefined]
_.castArray(null);
// => []
var array = [1, 2, 3];
// => trueCreates 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.
0.1.0
value(*): The value to clone.
(*): Returns the cloned value.
var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
// => trueThis method is like _.clone except that it recursively clones value.
1.0.0
value(*): The value to recursively clone.
(*): Returns the deep cloned value.
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
// => falseThis method is like _.cloneWith except that it recursively clones value.
4.0.0
customizer(Function): The function to customize cloning.value(*): The value to recursively clone.
(*): Returns the deep cloned value.
function customizer(value) {
if (_.isElement(value)) {
return value.cloneNode(true);
}
}
var el = _.cloneDeepWith(customizer, document.body);
// => false
// => 'BODY'
// => 20This 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]).
4.0.0
customizer(Function): The function to customize cloning.value(*): The value to clone.
(*): Returns the cloned value.
function customizer(value) {
if (_.isElement(value)) {
return value.cloneNode(false);
}
}
var el = _.cloneWith(customizer, document.body);
// => false
// => 'BODY'
// => 0Performs a
SameValueZero
comparison between two values to determine if they are equivalent.
4.0.0
value(*): The value to compare.other(*): The other value to compare.
(boolean): Returns true if the values are equivalent, else false.
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);
// => trueChecks if value is greater than other.
3.9.0
value(*): The value to compare.other(*): The other value to compare.
(boolean): Returns true if value is greater than other, else false.
_.gt(3, 1);
// => true
_.gt(3, 3);
// => false
_.gt(1, 3);
// => falseChecks if value is greater than or equal to other.
3.9.0
value(*): The value to compare.other(*): The other value to compare.
(boolean): Returns true if value is greater than or equal to other, else false.
_.gte(3, 1);
// => true
_.gte(3, 3);
// => true
_.gte(1, 3);
// => falseChecks if value is likely an arguments object.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isArguments(function() { return arguments; }());
// => true
_.isArguments([1, 2, 3]);
// => falseChecks if value is classified as an Array object.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isArray([1, 2, 3]);
// => true
_.isArray(document.body.children);
// => false
_.isArray('abc');
// => false
_.isArray(_.noop);
// => falseChecks if value is classified as an ArrayBuffer object.
4.3.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isArrayBuffer(new ArrayBuffer(2));
// => true
_.isArrayBuffer(new Array(2));
// => falseChecks 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.
4.0.0
value(*): The value to check.
(boolean): Returns true if value is array-like, else false.
_.isArrayLike([1, 2, 3]);
// => true
_.isArrayLike(document.body.children);
// => true
_.isArrayLike('abc');
// => true
_.isArrayLike(_.noop);
// => falseThis method is like _.isArrayLike except that it also checks if value
is an object.
4.0.0
value(*): The value to check.
(boolean): Returns true if value is an array-like object, else false.
_.isArrayLikeObject([1, 2, 3]);
// => true
_.isArrayLikeObject(document.body.children);
// => true
_.isArrayLikeObject('abc');
// => false
_.isArrayLikeObject(_.noop);
// => falseChecks if value is classified as a boolean primitive or object.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isBoolean(false);
// => true
_.isBoolean(null);
// => falseChecks if value is a buffer.
4.3.0
value(*): The value to check.
(boolean): Returns true if value is a buffer, else false.
_.isBuffer(new Buffer(2));
// => true
_.isBuffer(new Uint8Array(2));
// => falseChecks if value is classified as a Date object.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isDate(new Date);
// => true
_.isDate('Mon April 23 2012');
// => falseChecks if value is likely a DOM element.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is a DOM element, else false.
_.isElement(document.body);
// => true
_.isElement('<body>');
// => falseChecks if value is an empty object, collection, map, or set.
Objects are considered empty if they have no own enumerable string keyed
properties.
Array-like values such as arguments objects, arrays, buffers, strings, or
jQuery-like collections are considered empty if they have a length of 0.
Similarly, maps and sets are considered empty if they have a size of 0.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is empty, else false.
_.isEmpty(null);
// => true
_.isEmpty(true);
// => true
_.isEmpty(1);
// => true
_.isEmpty([1, 2, 3]);
// => false
_.isEmpty({ 'a': 1 });
// => falsePerforms 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.
0.1.0
value(*): The value to compare.other(*): The other value to compare.
(boolean): Returns true if the values are equivalent, else false.
var object = { 'user': 'fred' };
var other = { 'user': 'fred' };
_.isEqual(object, other);
// => true
object === other;
// => falseThis 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]).
4.0.0
customizer(Function): The function to customize comparisons.value(*): The value to compare.other(*): The other value to compare.
(boolean): Returns true if the values are equivalent, else false.
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(customizer, array, other);
// => trueChecks if value is an Error, EvalError, RangeError, ReferenceError,
SyntaxError, TypeError, or URIError object.
3.0.0
value(*): The value to check.
(boolean): Returns true if value is an error object, else false.
_.isError(new Error);
// => true
_.isError(Error);
// => falseChecks if value is a finite primitive number.
Note: This method is based on
Number.isFinite.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is a finite number, else false.
_.isFinite(3);
// => true
_.isFinite(Number.MIN_VALUE);
// => true
_.isFinite(Infinity);
// => false
_.isFinite('3');
// => falseChecks if value is classified as a Function object.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isFunction(_);
// => true
_.isFunction(/abc/);
// => falseChecks if value is an integer.
Note: This method is based on
Number.isInteger.
4.0.0
value(*): The value to check.
(boolean): Returns true if value is an integer, else false.
_.isInteger(3);
// => true
_.isInteger(Number.MIN_VALUE);
// => false
_.isInteger(Infinity);
// => false
_.isInteger('3');
// => falseChecks if value is a valid array-like length.
Note: This function is loosely based on
ToLength.
4.0.0
value(*): The value to check.
(boolean): Returns true if value is a valid length, else false.
_.isLength(3);
// => true
_.isLength(Number.MIN_VALUE);
// => false
_.isLength(Infinity);
// => false
_.isLength('3');
// => falseChecks if value is classified as a Map object.
4.3.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isMap(new Map);
// => true
_.isMap(new WeakMap);
// => falsePerforms 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.
3.0.0
source(Object): The object of property values to match.object(Object): The object to inspect.
(boolean): Returns true if object is a match, else false.
var object = { 'user': 'fred', 'age': 40 };
_.isMatch({ 'age': 40 }, object);
// => true
_.isMatch({ 'age': 36 }, object);
// => falseThis 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).
4.0.0
customizer(Function): The function to customize comparisons.source(Object): The object of property values to match.object(Object): The object to inspect.
(boolean): Returns true if object is a match, else false.
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(customizer, source, object);
// => trueChecks if value is NaN.
Note: This method is based on
Number.isNaN and is not the same as
global isNaN which returns true for
undefined and other non-number values.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is NaN, else false.
_.isNaN(NaN);
// => true
_.isNaN(new Number(NaN));
// => true
isNaN(undefined);
// => true
_.isNaN(undefined);
// => falseChecks if value is a pristine native function.
Note: This method can't reliably detect native functions in the
presence of the core-js package because core-js circumvents this kind
of detection. Despite multiple requests, the core-js maintainer has made
it clear: any attempt to fix the detection will be obstructed. As a result,
we're left with little choice but to throw an error. Unfortunately, this
also affects packages, like babel-polyfill,
which rely on core-js.
3.0.0
value(*): The value to check.
(boolean): Returns true if value is a native function, else false.
_.isNative(Array.prototype.push);
// => true
_.isNative(_);
// => falseChecks if value is null or undefined.
4.0.0
value(*): The value to check.
(boolean): Returns true if value is nullish, else false.
_.isNil(null);
// => true
_.isNil(void 0);
// => true
_.isNil(NaN);
// => falseChecks if value is null.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is null, else false.
_.isNull(null);
// => true
_.isNull(void 0);
// => falseChecks 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.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isNumber(3);
// => true
_.isNumber(Number.MIN_VALUE);
// => true
_.isNumber(Infinity);
// => true
_.isNumber('3');
// => falseChecks if value is the
language type
of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))
0.1.0
value(*): The value to check.
(boolean): Returns true if value is an object, else false.
_.isObject({});
// => true
_.isObject([1, 2, 3]);
// => true
_.isObject(_.noop);
// => true
_.isObject(null);
// => falseChecks if value is object-like. A value is object-like if it's not null
and has a typeof result of "object".
4.0.0
value(*): The value to check.
(boolean): Returns true if value is object-like, else false.
_.isObjectLike({});
// => true
_.isObjectLike([1, 2, 3]);
// => true
_.isObjectLike(_.noop);
// => false
_.isObjectLike(null);
// => falseChecks if value is a plain object, that is, an object created by the
Object constructor or one with a [[Prototype]] of null.
0.8.0
value(*): The value to check.
(boolean): Returns true if value is a plain object, else false.
function Foo() {
this.a = 1;
}
_.isPlainObject(new Foo);
// => false
_.isPlainObject([1, 2, 3]);
// => false
_.isPlainObject({ 'x': 0, 'y': 0 });
// => true
_.isPlainObject(Object.create(null));
// => trueChecks if value is classified as a RegExp object.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isRegExp(/abc/);
// => true
_.isRegExp('/abc/');
// => falseChecks 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.
4.0.0
value(*): The value to check.
(boolean): Returns true if value is a safe integer, else false.
_.isSafeInteger(3);
// => true
_.isSafeInteger(Number.MIN_VALUE);
// => false
_.isSafeInteger(Infinity);
// => false
_.isSafeInteger('3');
// => falseChecks if value is classified as a Set object.
4.3.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isSet(new Set);
// => true
_.isSet(new WeakSet);
// => falseChecks if value is classified as a String primitive or object.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isString('abc');
// => true
_.isString(1);
// => falseChecks if value is classified as a Symbol primitive or object.
4.0.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isSymbol(Symbol.iterator);
// => true
_.isSymbol('abc');
// => falseChecks if value is classified as a typed array.
3.0.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isTypedArray(new Uint8Array);
// => true
_.isTypedArray([]);
// => falseChecks if value is undefined.
0.1.0
value(*): The value to check.
(boolean): Returns true if value is undefined, else false.
_.isUndefined(void 0);
// => true
_.isUndefined(null);
// => falseChecks if value is classified as a WeakMap object.
4.3.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isWeakMap(new WeakMap);
// => true
_.isWeakMap(new Map);
// => falseChecks if value is classified as a WeakSet object.
4.3.0
value(*): The value to check.
(boolean): Returns true if value is correctly classified, else false.
_.isWeakSet(new WeakSet);
// => true
_.isWeakSet(new Set);
// => falseChecks if value is less than other.
3.9.0
value(*): The value to compare.other(*): The other value to compare.
(boolean): Returns true if value is less than other, else false.
_.lt(1, 3);
// => true
_.lt(3, 3);
// => false
_.lt(3, 1);
// => falseChecks if value is less than or equal to other.
3.9.0
value(*): The value to compare.other(*): The other value to compare.
(boolean): Returns true if value is less than or equal to other, else false.
_.lte(1, 3);
// => true
_.lte(3, 3);
// => true
_.lte(3, 1);
// => falseConverts value to an array.
0.1.0
value(*): The value to convert.
(Array): Returns the converted array.
_.toArray({ 'a': 1, 'b': 2 });
// => [1, 2]
_.toArray('abc');
// => ['a', 'b', 'c']
_.toArray(1);
// => []
_.toArray(null);
// => []Converts value to a finite number.
4.12.0
value(*): The value to convert.
(number): Returns the converted number.
_.toFinite(3.2);
// => 3.2
_.toFinite(Number.MIN_VALUE);
// => 5e-324
_.toFinite(Infinity);
// => 1.7976931348623157e+308
_.toFinite('3.2');
// => 3.2Converts value to an integer.
Note: This method is loosely based on
ToInteger.
4.0.0
value(*): The value to convert.
(number): Returns the converted integer.
_.toInteger(3.2);
// => 3
_.toInteger(Number.MIN_VALUE);
// => 0
_.toInteger(Infinity);
// => 1.7976931348623157e+308
_.toInteger('3.2');
// => 3Converts value to an integer suitable for use as the length of an
array-like object.
Note: This method is based on
ToLength.
4.0.0
value(*): The value to convert.
(number): Returns the converted integer.
_.toLength(3.2);
// => 3
_.toLength(Number.MIN_VALUE);
// => 0
_.toLength(Infinity);
// => 4294967295
_.toLength('3.2');
// => 3Converts value to a number.
4.0.0
value(*): The value to process.
(number): Returns the number.
_.toNumber(3.2);
// => 3.2
_.toNumber(Number.MIN_VALUE);
// => 5e-324
_.toNumber(Infinity);
// => Infinity
_.toNumber('3.2');
// => 3.2Converts value to a plain object flattening inherited enumerable string
keyed properties of value to own properties of the plain object.
3.0.0
value(*): The value to convert.
(Object): Returns the converted plain object.
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 }Converts value to a safe integer. A safe integer can be compared and
represented correctly.
4.0.0
value(*): The value to convert.
(number): Returns the converted integer.
_.toSafeInteger(3.2);
// => 3
_.toSafeInteger(Number.MIN_VALUE);
// => 0
_.toSafeInteger(Infinity);
// => 9007199254740991
_.toSafeInteger('3.2');
// => 3Converts value to a string. An empty string is returned for null
and undefined values. The sign of -0 is preserved.
4.0.0
value(*): The value to process.
(string): Returns the string.
_.toString(null);
// => ''
_.toString(-0);
// => '-0'
_.toString([1, 2, 3]);
// => '1,2,3'Adds two numbers.
3.4.0
augend(number): The first number in an addition.addend(number): The second number in an addition.
(number): Returns the total.
_.add(6, 4);
// => 10Computes number rounded up to precision.
3.10.0
number(number): The number to round up.
(number): Returns the rounded up number.
_.ceil(4.006);
// => 5
_.ceil([6.004, 2]);
// => 6.01
_.ceil([6040, -2]);
// => 6100Divide two numbers.
4.7.0
dividend(number): The first number in a division.divisor(number): The second number in a division.
(number): Returns the quotient.
_.divide(6, 4);
// => 1.5Computes number rounded down to precision.
3.10.0
number(number): The number to round down.
(number): Returns the rounded down number.
_.floor(4.006);
// => 4
_.floor([0.046, 2]);
// => 0.04
_.floor([4060, -2]);
// => 4000Computes the maximum value of array. If array is empty or falsey,
undefined is returned.
0.1.0
array(Array): The array to iterate over.
(*): Returns the maximum value.
_.max([4, 2, 8, 6]);
// => 8
_.max([]);
// => undefinedThis 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).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.array(Array): The array to iterate over.
(*): Returns the maximum value.
var objects = [{ 'n': 1 }, { 'n': 2 }];
_.maxBy(function(o) { return o.n; }, objects);
// => { 'n': 2 }
// The `_.property` iteratee shorthand.
_.maxBy('n', objects);
// => { 'n': 2 }Computes the mean of the values in array.
4.0.0
array(Array): The array to iterate over.
(number): Returns the mean.
_.mean([4, 2, 8, 6]);
// => 5This method is like _.mean except that it accepts iteratee which is
invoked for each element in array to generate the value to be averaged.
The iteratee is invoked with one argument: (value).
4.7.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.array(Array): The array to iterate over.
(number): Returns the mean.
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.meanBy(function(o) { return o.n; }, objects);
// => 5
// The `_.property` iteratee shorthand.
_.meanBy('n', objects);
// => 5Computes the minimum value of array. If array is empty or falsey,
undefined is returned.
0.1.0
array(Array): The array to iterate over.
(*): Returns the minimum value.
_.min([4, 2, 8, 6]);
// => 2
_.min([]);
// => undefinedThis 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).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.array(Array): The array to iterate over.
(*): Returns the minimum value.
var objects = [{ 'n': 1 }, { 'n': 2 }];
_.minBy(function(o) { return o.n; }, objects);
// => { 'n': 1 }
// The `_.property` iteratee shorthand.
_.minBy('n', objects);
// => { 'n': 1 }Multiply two numbers.
4.7.0
multiplier(number): The first number in a multiplication.multiplicand(number): The second number in a multiplication.
(number): Returns the product.
_.multiply(6, 4);
// => 24Computes number rounded to precision.
3.10.0
number(number): The number to round.
(number): Returns the rounded number.
_.round(4.006);
// => 4
_.round([4.006, 2]);
// => 4.01
_.round([4060, -2]);
// => 4100Subtract two numbers.
4.0.0
minuend(number): The first number in a subtraction.subtrahend(number): The second number in a subtraction.
(number): Returns the difference.
_.subtract(6, 4);
// => 2Computes the sum of the values in array.
3.4.0
array(Array): The array to iterate over.
(number): Returns the sum.
_.sum([4, 2, 8, 6]);
// => 20This 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).
4.0.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.array(Array): The array to iterate over.
(number): Returns the sum.
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.sumBy(function(o) { return o.n; }, objects);
// => 20
// The `_.property` iteratee shorthand.
_.sumBy('n', objects);
// => 20Clamps number within the inclusive lower and upper bounds.
4.0.0
lower(number): The lower bound.upper(number): The upper bound.number(number): The number to clamp.
(number): Returns the clamped number.
_.clamp(-5, 5, -10);
// => -5
_.clamp(-5, 5, 10);
// => 5Checks 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.
3.3.0
start(number): The start of the range.end(number): The end of the range.number(number): The number to check.
(boolean): Returns true if number is in the range, else false.
_.inRange(2, 4, 3);
// => true
_.inRange(0, 8, 4);
// => true
_.inRange(0, 2, 4);
// => false
_.inRange(0, 2, 2);
// => false
_.inRange(0, 2, 1.2);
// => true
_.inRange(0, 4, 5.2);
// => false
_.inRange(-2, -6, -3);
// => trueProduces 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.
0.7.0
lower(number): The lower bound.upper(number): The upper bound.
(number): Returns the random number.
_.random(0, 5);
// => an integer between 0 and 5
_.random(5, 1);
// => 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.2Assigns own enumerable string keyed properties of source objects to the destination object. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
0.10.0
object(Object): The destination object.sources(Object|Object[]): The source objects.
(Object): Returns object.
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 }This method is like _.assign except that it iterates over own and
inherited source properties.
4.0.0
_.extend
object(Object): The destination object.sources(Object|Object[]): The source objects.
(Object): Returns object.
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 }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).
4.0.0
_.extendWith
customizer(Function): The function to customize assigned values.object(Object): The destination object.sources(Object|Object[]): The source objects.
(Object): Returns object.
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 }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).
4.0.0
customizer(Function): The function to customize assigned values.object(Object): The destination object.sources(Object|Object[]): The source objects.
(Object): Returns object.
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 }Creates an array of values corresponding to paths of object.
1.0.0
paths(string|string[]): The property paths of elements to pick.object(Object): The object to iterate over.
(Array): Returns the picked values.
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
_.at(['a[0].b.c', 'a[1]'], object);
// => [3, 4]Creates an object that inherits from the prototype object. If a
properties object is given, its own enumerable string keyed properties
are assigned to the created object.
2.3.0
prototype(Object): The object to inherit from.
(Object): Returns the new object.
function Shape() {
this.x = 0;
this.y = 0;
}
function Circle() {
Shape.call(this);
}
Circle.prototype = _.create([Shape.prototype, {
'constructor': Circle
}]);
var circle = new Circle;
circle instanceof Circle;
// => true
circle instanceof Shape;
// => trueAssigns own and inherited enumerable string keyed 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.
0.1.0
sources(Object|Object[]): The source objects.object(Object): The destination object.
(Object): Returns object.
_.defaults([{ 'age': 36 }, { 'user': 'fred' }], { 'user': 'barney' });
// => { 'user': 'barney', 'age': 36 }This method is like _.defaults except that it recursively assigns
default properties.
3.10.0
sources(Object|Object[]): The source objects.object(Object): The destination object.
(Object): Returns object.
_.defaultsDeep(
{ 'user': { 'name': 'fred', 'age': 36 } },
{ 'user': { 'name': 'barney' } }
);
// => { 'user': { 'name': 'barney', 'age': 36 } }This method is like _.find except that it returns the key of the first
element predicate returns truthy for instead of the element itself.
1.1.0
predicate(Array|Function|Object|string): The function invoked per iteration.object(Object): The object to search.
(*): Returns the key of the matched element, else undefined.
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findKey(function(o) { return o.age < 40; }, users);
// => 'barney' (iteration order is not guaranteed)
// The `_.matches` iteratee shorthand.
_.findKey({ 'age': 1, 'active': true }, users);
// => 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.findKey(['active', false], users);
// => 'fred'
// The `_.property` iteratee shorthand.
_.findKey('active', users);
// => 'barney'This method is like _.findKey except that it iterates over elements of
a collection in the opposite order.
2.0.0
predicate(Array|Function|Object|string): The function invoked per iteration.object(Object): The object to search.
(*): Returns the key of the matched element, else undefined.
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findLastKey(function(o) { return o.age < 40; }, users);
// => returns 'pebbles' assuming `_.findKey` returns 'barney'
// The `_.matches` iteratee shorthand.
_.findLastKey({ 'age': 36, 'active': true }, users);
// => 'barney'
// The `_.matchesProperty` iteratee shorthand.
_.findLastKey(['active', false], users);
// => 'fred'
// The `_.property` iteratee shorthand.
_.findLastKey('active', users);
// => 'pebbles'Iterates over own and inherited enumerable string keyed properties of an
object and invokes iteratee for each property. The iteratee is invoked
with three arguments: (value, key, object). Iteratee functions may exit
iteration early by explicitly returning false.
0.3.0
iteratee(Function): The function invoked per iteration.object(Object): The object to iterate over.
(Object): Returns object.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forIn(function(value, key) {
console.log(key);
}, new Foo);
// => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).This method is like _.forIn except that it iterates over properties of
object in the opposite order.
2.0.0
iteratee(Function): The function invoked per iteration.object(Object): The object to iterate over.
(Object): Returns object.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forInRight(function(value, key) {
console.log(key);
}, new Foo);
// => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.Iterates over own enumerable string keyed properties of an object and
invokes iteratee for each property. The iteratee is invoked with three
arguments: (value, key, object). Iteratee functions may exit iteration
early by explicitly returning false.
0.3.0
iteratee(Function): The function invoked per iteration.object(Object): The object to iterate over.
(Object): Returns object.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forOwn(function(value, key) {
console.log(key);
}, new Foo);
// => Logs 'a' then 'b' (iteration order is not guaranteed).This method is like _.forOwn except that it iterates over properties of
object in the opposite order.
2.0.0
iteratee(Function): The function invoked per iteration.object(Object): The object to iterate over.
(Object): Returns object.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forOwnRight(function(value, key) {
console.log(key);
}, new Foo);
// => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.Creates an array of function property names from own enumerable properties
of object.
0.1.0
object(Object): The object to inspect.
(Array): Returns the function names.
function Foo() {
this.a = _.constant('a');
this.b = _.constant('b');
}
Foo.prototype.c = _.constant('c');
_.functions(new Foo);
// => ['a', 'b']Creates an array of function property names from own and inherited
enumerable properties of object.
4.0.0
object(Object): The object to inspect.
(Array): Returns the function names.
function Foo() {
this.a = _.constant('a');
this.b = _.constant('b');
}
Foo.prototype.c = _.constant('c');
_.functionsIn(new Foo);
// => ['a', 'b', 'c']Gets the value at path of object. If the resolved value is
undefined, the defaultValue is used in its place.
3.7.0
path(Array|string): The path of the property to get.object(Object): The object to query.
(*): Returns the resolved value.
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get('a[0].b.c', object);
// => 3
_.get(['a', '0', 'b', 'c'], object);
// => 3
_.get(['a.b.c', 'default'], object);
// => 'default'Checks if path is a direct property of object.
0.1.0
path(Array|string): The path to check.object(Object): The object to query.
(boolean): Returns true if path exists, else false.
var object = { 'a': { 'b': 2 } };
var other = _.create({ 'a': _.create({ 'b': 2 }) });
_.has('a', object);
// => true
_.has('a.b', object);
// => true
_.has(['a', 'b'], object);
// => true
_.has('a', other);
// => falseChecks if path is a direct or inherited property of object.
4.0.0
path(Array|string): The path to check.object(Object): The object to query.
(boolean): Returns true if path exists, else false.
var object = _.create({ 'a': _.create({ 'b': 2 }) });
_.hasIn('a', object);
// => true
_.hasIn('a.b', object);
// => true
_.hasIn(['a', 'b'], object);
// => true
_.hasIn('b', object);
// => falseCreates an object composed of the inverted keys and values of object.
If object contains duplicate values, subsequent values overwrite
property assignments of previous values.
0.7.0
object(Object): The object to invert.
(Object): Returns the new inverted object.
var object = { 'a': 1, 'b': 2, 'c': 1 };
_.invert(object);
// => { '1': 'c', '2': 'b' }This method is like _.invert except that the inverted object is generated
from the results of running each element of object thru 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).
4.1.0
iteratee(Array|Function|Object|string): The iteratee invoked per element.object(Object): The object to invert.
(Object): Returns the new inverted object.
var object = { 'a': 1, 'b': 2, 'c': 1 };
_.invertBy(_.identity, object);
// => { '1': ['a', 'c'], '2': ['b'] }
_.invertBy(function(value) {
return 'group' + value;
}, object);
// => { 'group1': ['a', 'c'], 'group2': ['b'] }Invokes the method at path of object.
4.0.0
path(Array|string): The path of the method to invoke.object(Object): The object to query.
(*): Returns the result of the invoked method.
var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
_.invoke(['a[0].b.c.slice', 1, 3], object);
// => [2, 3]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.
0.1.0
object(Object): The object to query.
(Array): Returns the array of property names.
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']Creates an array of the own and inherited enumerable property names of object.
Note: Non-object values are coerced to objects.
3.0.0
object(Object): The object to query.
(Array): Returns the array of property names.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.keysIn(new Foo);
// => ['a', 'b', 'c'] (iteration order is not guaranteed)The opposite of _.mapValues; this method creates an object with the
same values as object and keys generated by running each own enumerable
string keyed property of object thru iteratee. The iteratee is invoked
with three arguments: (value, key, object).
3.8.0
iteratee(Array|Function|Object|string): The function invoked per iteration.object(Object): The object to iterate over.
(Object): Returns the new mapped object.
_.mapKeys(function(value, key) {
return key + value;
}, { 'a': 1, 'b': 2 });
// => { 'a1': 1, 'b2': 2 }Creates an object with the same keys as object and values generated
by running each own enumerable string keyed property of object thru
iteratee. The iteratee is invoked with three arguments:
(value, key, object).
2.4.0
iteratee(Array|Function|Object|string): The function invoked per iteration.object(Object): The object to iterate over.
(Object): Returns the new mapped object.
var users = {
'fred': { 'user': 'fred', 'age': 40 },
'pebbles': { 'user': 'pebbles', 'age': 1 }
};
_.mapValues(function(o) { return o.age; }, users);
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
// The `_.property` iteratee shorthand.
_.mapValues('age', users);
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)This method is like _.assign except that it recursively merges own and
inherited enumerable string keyed 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.
0.5.0
object(Object): The destination object.sources(Object|Object[]): The source objects.
(Object): Returns object.
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 }] }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).
4.0.0
customizer(Function): The function to customize assigned values.object(Object): The destination object.sources(Object|Object[]): The source objects.
(Object): Returns object.
function customizer(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
}
var object = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var other = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.mergeWith(customizer, object, other);
// => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }The opposite of _.pick; this method creates an object composed of the
own and inherited enumerable string keyed properties of object that are
not omitted.
0.1.0
props(string|string[]): The property identifiers to omit.object(Object): The source object.
(Object): Returns the new object.
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.omit(['a', 'c'], object);
// => { 'b': '2' }The opposite of _.pickBy; this method creates an object composed of
the own and inherited enumerable string keyed properties of object that
predicate doesn't return truthy for. The predicate is invoked with two
arguments: (value, key).
4.0.0
predicate(Array|Function|Object|string): The function invoked per property.object(Object): The source object.
(Object): Returns the new object.
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.omitBy(_.isNumber, object);
// => { 'b': '2' }Creates an object composed of the picked object properties.
0.1.0
props(string|string[]): The property identifiers to pick.object(Object): The source object.
(Object): Returns the new object.
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.pick(['a', 'c'], object);
// => { 'a': 1, 'c': 3 }Creates an object composed of the object properties predicate returns
truthy for. The predicate is invoked with two arguments: (value, key).
4.0.0
predicate(Array|Function|Object|string): The function invoked per property.object(Object): The source object.
(Object): Returns the new object.
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.pickBy(_.isNumber, object);
// => { 'a': 1, 'c': 3 }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.
0.1.0
path(Array|string): The path of the property to resolve.object(Object): The object to query.
(*): Returns the resolved value.
var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
_.result('a[0].b.c1', object);
// => 3
_.result('a[0].b.c2', object);
// => 4
_.result(['a[0].b.c3', 'default'], object);
// => 'default'
_.result(['a[0].b.c3', _.constant('default')], object);
// => 'default'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.
3.7.0
path(Array|string): The path of the property to set.value(*): The value to set.object(Object): The object to modify.
(Object): Returns object.
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set('a[0].b.c', 4, object);
// => 4
_.set(['x', '0', 'y', 'z'], 5, object);
// => 5This 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).
4.0.0
customizer(Function): The function to customize assigned values.path(Array|string): The path of the property to set.value(*): The value to set.object(Object): The object to modify.
(Object): Returns object.
var object = {};
_.setWith(Object, '[0][1]', 'a', object);
// => { '0': { '1': 'a' } }Creates an array of own enumerable string keyed-value pairs for object
which can be consumed by _.fromPairs. If object is a map or set, its
entries are returned.
4.0.0
_.entries
object(Object): The object to query.
(Array): Returns the key-value pairs.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.toPairs(new Foo);
// => [['a', 1], ['b', 2]] (iteration order is not guaranteed)Creates an array of own and inherited enumerable string keyed-value pairs
for object which can be consumed by _.fromPairs. If object is a map
or set, its entries are returned.
4.0.0
_.entriesIn
object(Object): The object to query.
(Array): Returns the key-value pairs.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.toPairsIn(new Foo);
// => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)An alternative to _.reduce; this method transforms object to a new
accumulator object which is the result of running each of its own
enumerable string keyed properties thru iteratee, with each invocation
potentially mutating the accumulator object. If accumulator is not
provided, a new object with the same [[Prototype]] will be used. The
iteratee is invoked with four arguments: (accumulator, value, key, object).
Iteratee functions may exit iteration early by explicitly returning false.
1.3.0
iteratee(Function): The function invoked per iteration.accumulator(*): The custom accumulator value.object(Object): The object to iterate over.
(*): Returns the accumulated value.
_.transform(function(result, n) {
result.push(n *= n);
return n % 2 == 0;
}, [], [2, 3, 4]);
// => [4, 9]
_.transform(function(result, value, key) {
(result[value] || (result[value] = [])).push(key);
}, {}, { 'a': 1, 'b': 2, 'c': 1 });
// => { '1': ['a', 'c'], '2': ['b'] }Removes the property at path of object.
4.0.0
path(Array|string): The path of the property to unset.object(Object): The object to modify.
(boolean): Returns true if the property is deleted, else false.
var object = { 'a': [{ 'b': { 'c': 7 } }] };
_.unset('a[0].b.c', object);
// => true
// => { 'a': [{ 'b': {} }] };
_.unset(['a', '0', 'b', 'c'], object);
// => true
// => { 'a': [{ 'b': {} }] };This method is like _.set except that accepts updater to produce the
value to set. Use _.updateWith to customize path creation. The updater
is invoked with one argument: (value).
4.6.0
path(Array|string): The path of the property to set.updater(Function): The function to produce the updated value.object(Object): The object to modify.
(Object): Returns object.
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.update('a[0].b.c', function(n) { return n * n; }, object);
// => 9
_.update('x[0].y.z', function(n) { return n ? n + 1 : 0; }, object);
// => 0This method is like _.update 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).
4.6.0
customizer(Function): The function to customize assigned values.path(Array|string): The path of the property to set.updater(Function): The function to produce the updated value.object(Object): The object to modify.
(Object): Returns object.
var object = {};
_.updateWith(Object, '[0][1]', _.constant('a'), object);
// => { '0': { '1': 'a' } }Creates an array of the own enumerable string keyed property values of object.
Note: Non-object values are coerced to objects.
0.1.0
object(Object): The object to query.
(Array): Returns the array of property values.
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']Creates an array of the own and inherited enumerable string keyed property
values of object.
Note: Non-object values are coerced to objects.
3.0.0
object(Object): The object to query.
(Array): Returns the array of property values.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.valuesIn(new Foo);
// => [1, 2, 3] (iteration order is not guaranteed)Creates a lodash object which wraps value to enable implicit method
chain sequences. 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 chain sequences, which must be unwrapped with _#value, 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 200 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, extend, extendWith, fill, filter,
flatMap, flatMapDeep, flatMapDepth, 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,
pullAllWith, 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, update, updateWith, 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, divide, each,
eachRight, endsWith, eq, escape, escapeRegExp, every, find,
findIndex, findKey, findLast, findLastIndex, findLastKey, first,
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, meanBy,
min, minBy, multiply, noConflict, noop, now, nth, pad,
padEnd, padStart, parseInt, pop, random, reduce, reduceRight,
repeat, result, round, runInContext, sample, shift, size,
snakeCase, some, sortedIndex, sortedIndexBy, sortedLastIndex,
sortedLastIndexBy, startCase, startsWith, stubArray, stubFalse,
stubObject, stubString, stubTrue, subtract, sum, sumBy,
template, times, toFinite, toInteger, toJSON, toLength,
toLower, toNumber, toSafeInteger, toString, toUpper, trim,
trimEnd, trimStart, truncate, unescape, uniqueId, upperCase,
upperFirst, value, and words
(Object): Returns the new lodash wrapper instance.
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());
// => trueCreates a lodash wrapper instance that wraps value with explicit method
chain sequences enabled. The result of such sequences must be unwrapped
with _#value.
1.3.0
value(*): The value to wrap.
(Object): Returns the new lodash wrapper instance.
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'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 sequence in order to modify intermediate results.
0.1.0
interceptor(Function): The function to invoke.value(*): The value to provide tointerceptor.
(*): Returns value.
_([1, 2, 3])
.tap(function(array) {
// Mutate input array.
array.pop();
})
.reverse()
.value();
// => [2, 1]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 sequence.
3.0.0
interceptor(Function): The function to invoke.value(*): The value to provide tointerceptor.
(*): Returns the result of interceptor.
_(' abc ')
.chain()
.trim()
.thru(function(value) {
return [value];
})
.value();
// => ['abc']Enables the wrapper to be iterable.
4.0.0
(Object): Returns the wrapper object.
var wrapped = _([1, 2]);
wrapped[Symbol.iterator]() === wrapped;
// => true
Array.from(wrapped);
// => [1, 2]This method is the wrapper version of _.at.
1.0.0
(Object): Returns the new lodash wrapper instance.
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
_(object).at(['a[0].b.c', 'a[1]']).value();
// => [3, 4]Creates a lodash wrapper instance with explicit method chain sequences enabled.
0.1.0
(Object): Returns the new lodash wrapper instance.
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' }Executes the chain sequence and returns the wrapped result.
3.2.0
(Object): Returns the new lodash wrapper instance.
var array = [1, 2];
var wrapped = _(array).push(3);
// => [1, 2]
wrapped = wrapped.commit();
// => [1, 2, 3]
wrapped.last();
// => 3
// => [1, 2, 3]Gets the next value on a wrapped object following the iterator protocol.
4.0.0
(Object): Returns the next iterator value.
var wrapped = _([1, 2]);
wrapped.next();
// => { 'done': false, 'value': 1 }
wrapped.next();
// => { 'done': false, 'value': 2 }
wrapped.next();
// => { 'done': true, 'value': undefined }Creates a clone of the chain sequence planting value as the wrapped value.
3.2.0
(Object): Returns the new lodash wrapper instance.
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]This method is the wrapper version of _.reverse.
0.1.0
(Object): Returns the new lodash wrapper instance.
var array = [1, 2, 3];
_(array).reverse().value()
// => [3, 2, 1]
// => [3, 2, 1]Executes the chain sequence to resolve the unwrapped value.
0.1.0
_.prototype.toJSON, _.prototype.valueOf
(*): Returns the resolved unwrapped value.
_([1, 2, 3]).value();
// => [1, 2, 3]Converts string to camel case.
3.0.0
string(string): The string to convert.
(string): Returns the camel cased string.
_.camelCase('Foo Bar');
// => 'fooBar'
_.camelCase('--foo-bar--');
// => 'fooBar'
_.camelCase('__FOO_BAR__');
// => 'fooBar'Converts the first character of string to upper case and the remaining
to lower case.
3.0.0
string(string): The string to capitalize.
(string): Returns the capitalized string.
_.capitalize('FRED');
// => 'Fred'Deburrs string by converting
latin-1 supplementary letters
to basic latin letters and removing
combining diacritical marks.
3.0.0
string(string): The string to deburr.
(string): Returns the deburred string.
_.deburr('déjà vu');
// => 'deja vu'Checks if string ends with the given target string.
3.0.0
target(string): The string to search for.string(string): The string to search.
(boolean): Returns true if string ends with target, else false.
_.endsWith('c', 'abc');
// => true
_.endsWith('b', 'abc');
// => false
_.endsWith(['b', 2], 'abc');
// => trueConverts 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.
0.1.0
string(string): The string to escape.
(string): Returns the escaped string.
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'Escapes the RegExp special characters "^", "$", "", ".", "*", "+",
"?", "(", ")", "[", "]", "{", "}", and "|" in string.
3.0.0
string(string): The string to escape.
(string): Returns the escaped string.
_.escapeRegExp('[lodash](https://lodash.com/)');
// => '\[lodash\]\(https://lodash\.com/\)'Converts string to
kebab case.
3.0.0
string(string): The string to convert.
(string): Returns the kebab cased string.
_.kebabCase('Foo Bar');
// => 'foo-bar'
_.kebabCase('fooBar');
// => 'foo-bar'
_.kebabCase('__FOO_BAR__');
// => 'foo-bar'Converts string, as space separated words, to lower case.
4.0.0
string(string): The string to convert.
(string): Returns the lower cased string.
_.lowerCase('--Foo-Bar--');
// => 'foo bar'
_.lowerCase('fooBar');
// => 'foo bar'
_.lowerCase('__FOO_BAR__');
// => 'foo bar'Converts the first character of string to lower case.
4.0.0
string(string): The string to convert.
(string): Returns the converted string.
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'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.
3.0.0
length(number): The padding length.string(string): The string to pad.
(string): Returns the padded string.
_.pad(8, 'abc');
// => ' abc '
_.pad([8, '_-'], 'abc');
// => '_-abc_-_'
_.pad(3, 'abc');
// => 'abc'Pads string on the right side if it's shorter than length. Padding
characters are truncated if they exceed length.
4.0.0
length(number): The padding length.string(string): The string to pad.
(string): Returns the padded string.
_.padEnd(6, 'abc');
// => 'abc '
_.padEnd([6, '_-'], 'abc');
// => 'abc_-_'
_.padEnd(3, 'abc');
// => 'abc'Pads string on the left side if it's shorter than length. Padding
characters are truncated if they exceed length.
4.0.0
length(number): The padding length.string(string): The string to pad.
(string): Returns the padded string.
_.padStart(6, 'abc');
// => ' abc'
_.padStart([6, '_-'], 'abc');
// => '_-_abc'
_.padStart(3, 'abc');
// => 'abc'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.
1.1.0
radix(number): The radix to interpretvalueby.string(string): The string to convert.
(number): Returns the converted integer.
_.parseInt(10, '08');
// => 8
_.map(_.parseInt, ['6', '08', '10']);
// => [6, 8, 10]Repeats the given string n times.
3.0.0
n(number): The number of times to repeat the string.string(string): The string to repeat.
(string): Returns the repeated string.
_.repeat(3, '*');
// => '***'
_.repeat(2, 'abc');
// => 'abcabc'
_.repeat(0, 'abc');
// => ''Replaces matches for pattern in string with replacement.
Note: This method is based on
String#replace.
4.0.0
pattern(RegExp|string): The pattern to replace.replacement(Function|string): The match replacement.string(string): The string to modify.
(string): Returns the modified string.
_.replace('Fred', 'Barney', 'Hi Fred');
// => 'Hi Barney'Converts string to
snake case.
3.0.0
string(string): The string to convert.
(string): Returns the snake cased string.
_.snakeCase('Foo Bar');
// => 'foo_bar'
_.snakeCase('fooBar');
// => 'foo_bar'
_.snakeCase('--FOO-BAR--');
// => 'foo_bar'Splits string by separator.
Note: This method is based on
String#split.
4.0.0
separator(RegExp|string): The separator pattern to split by.string(string): The string to split.
(Array): Returns the string segments.
_.split(['-', 2], 'a-b-c');
// => ['a', 'b']Converts string to
start case.
3.1.0
string(string): The string to convert.
(string): Returns the start cased string.
_.startCase('--foo-bar--');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__FOO_BAR__');
// => 'FOO BAR'Checks if string starts with the given target string.
3.0.0
target(string): The string to search for.string(string): The string to search.
(boolean): Returns true if string starts with target, else false.
_.startsWith('a', 'abc');
// => true
_.startsWith('b', 'abc');
// => false
_.startsWith(['b', 1], 'abc');
// => trueCreates 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.
0.1.0
string(string): The template string.
(Function): Returns the compiled template function.
// 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 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 custom template delimiters.
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'
// Use the `source` property to inline compiled templates for meaningful
// line numbers in error messages and stack traces.
fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
var JST = {\
"main": ' + _.template(mainText).source + '\
};\
');Converts string, as a whole, to lower case just like
String#toLowerCase.
4.0.0
string(string): The string to convert.
(string): Returns the lower cased string.
_.toLower('--Foo-Bar--');
// => '--foo-bar--'
_.toLower('fooBar');
// => 'foobar'
_.toLower('__FOO_BAR__');
// => '__foo_bar__'Converts string, as a whole, to upper case just like
String#toUpperCase.
4.0.0
string(string): The string to convert.
(string): Returns the upper cased string.
_.toUpper('--foo-bar--');
// => '--FOO-BAR--'
_.toUpper('fooBar');
// => 'FOOBAR'
_.toUpper('__foo_bar__');
// => '__FOO_BAR__'Removes leading and trailing whitespace or specified characters from string.
3.0.0
string(string): The string to trim.
(string): Returns the trimmed string.
_.trim(' abc ');
// => 'abc'
_.trim(['-_-abc-_-', '_-']);
// => 'abc'
_.map(_.trim, [' foo ', ' bar ']);
// => ['foo', 'bar']Removes trailing whitespace or specified characters from string.
4.0.0
string(string): The string to trim.
(string): Returns the trimmed string.
_.trimEnd(' abc ');
// => ' abc'
_.trimEnd(['-_-abc-_-', '_-']);
// => '-_-abc'Removes leading whitespace or specified characters from string.
4.0.0
string(string): The string to trim.
(string): Returns the trimmed string.
_.trimStart(' abc ');
// => 'abc '
_.trimStart(['-_-abc-_-', '_-']);
// => 'abc-_-'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 "...".
4.0.0
options(Object): The options object.string(string): The string to truncate.
(string): Returns the truncated string.
_.truncate({}, 'hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'
_.truncate({
'length': 24,
'separator': ' '
}, 'hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there,...'
_.truncate({
'length': 24,
'separator': /,? +/
}, 'hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there...'
_.truncate({
'omission': ' [...]'
}, 'hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neig [...]'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.
0.6.0
string(string): The string to unescape.
(string): Returns the unescaped string.
_.unescape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'Converts string, as space separated words, to upper case.
4.0.0
string(string): The string to convert.
(string): Returns the upper cased string.
_.upperCase('--foo-bar');
// => 'FOO BAR'
_.upperCase('fooBar');
// => 'FOO BAR'
_.upperCase('__foo_bar__');
// => 'FOO BAR'Converts the first character of string to upper case.
4.0.0
string(string): The string to convert.
(string): Returns the converted string.
_.upperFirst('fred');
// => 'Fred'
_.upperFirst('FRED');
// => 'FRED'Splits string into an array of its words.
3.0.0
string(string): The string to inspect.
(Array): Returns the words of string.
_.words('fred, barney, & pebbles');
// => ['fred', 'barney', 'pebbles']
_.words(['fred, barney, & pebbles', /[^, ]+/g]);
// => ['fred', 'barney', '&', 'pebbles']Attempts to invoke func, returning either the result or the caught error
object. Any additional arguments are provided to func when it's invoked.
3.0.0
func(Function): The function to attempt.
(*): Returns the func result or error object.
// Avoid throwing errors for invalid selectors.
var elements = _.attempt([function(selector) {
return document.querySelectorAll(selector);
}, '>_>']);
if (_.isError(elements)) {
elements = [];
}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.
0.1.0
methodNames(string|string[]): The object method names to bind.object(Object): The object to bind and assign the bound methods to.
(Object): Returns object.
var view = {
'label': 'docs',
'onClick': function() {
console.log('clicked ' + this.label);
}
};
_.bindAll(['onClick'], view);
jQuery(element).on('click', view.onClick);
// => Logs 'clicked docs' when clicked.Creates a function that iterates over pairs and invokes 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.
4.0.0
pairs(Array): The predicate-function pairs.
(Function): Returns the new composite function.
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'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.
4.0.0
source(Object): The object of property predicates to conform to.
(Function): Returns the new spec function.
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
_.filter(_.conforms({ 'age': function(n) { return n > 38; } }), users);
// => [{ 'user': 'fred', 'age': 40 }]Creates a function that returns value.
2.4.0
value(*): The value to return from the new function.
(Function): Returns the new constant function.
var objects = _.times(_.constant({ 'a': 1 }), 2);
// => [{ 'a': 1 }, { 'a': 1 }]
// => trueCreates 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.
3.0.0
funcs(Function|Function[]): Functions to invoke.
(Function): Returns the new composite function.
function square(n) {
return n * n;
}
var addSquare = _.flow([_.add, square]);
addSquare(1, 2);
// => 9This method is like _.flow except that it creates a function that
invokes the given functions from right to left.
3.0.0
funcs(Function|Function[]): Functions to invoke.
(Function): Returns the new composite function.
function square(n) {
return n * n;
}
var addSquare = _.flowRight([square, _.add]);
addSquare(1, 2);
// => 9This method returns the first argument given to it.
0.1.0
value(*): Any value.
(*): Returns value.
var object = { 'user': 'fred' };
// => trueCreates a function that invokes func with the arguments of the created
function. If func is a property name, the created function returns the
property value for a given element. If func is an array or object, the
created function returns true for elements that contain the equivalent
source properties, otherwise it returns false.
4.0.0
func(*): The value to convert to a callback.
(Function): Returns the callback.
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
// The `_.matches` iteratee shorthand.
_.filter(_.iteratee({ 'user': 'barney', 'active': true }), users);
// => [{ 'user': 'barney', 'age': 36, 'active': true }]
// The `_.matchesProperty` iteratee shorthand.
_.filter(_.iteratee(['user', 'fred']), users);
// => [{ 'user': 'fred', 'age': 40 }]
// The `_.property` iteratee shorthand.
_.map(_.iteratee('user'), users);
// => ['barney', 'fred']
// Create custom iteratee shorthands.
_.iteratee = _.wrap(function(iteratee, func) {
return !_.isRegExp(func) ? iteratee(func) : function(string) {
return func.test(string);
};
}, _.iteratee);
_.filter(/ef/, ['abc', 'def']);
// => ['def']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.
3.0.0
source(Object): The object of property values to match.
(Function): Returns the new spec function.
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(_.matches({ 'age': 40, 'active': false }), users);
// => [{ 'user': 'fred', 'age': 40, 'active': false }]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.
3.2.0
path(Array|string): The path of the property to get.srcValue(*): The value to match.
(Function): Returns the new spec function.
var users = [
{ 'user': 'barney' },
{ 'user': 'fred' }
];
_.find(_.matchesProperty('user', 'fred'), users);
// => { 'user': 'fred' }Creates a function that invokes the method at path of a given object.
Any additional arguments are provided to the invoked method.
3.7.0
path(Array|string): The path of the method to invoke.
(Function): Returns the new invoker function.
var objects = [
{ 'a': { 'b': _.constant(2) } },
{ 'a': { 'b': _.constant(1) } }
];
_.map(_.method('a.b'), objects);
// => [2, 1]
_.map(_.method(['a', 'b']), objects);
// => [2, 1]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.
3.7.0
object(Object): The object to query.
(Function): Returns the new invoker function.
var array = _.times(_.constant, 3),
object = { 'a': array, 'b': array, 'c': array };
_.map(_.methodOf(object), ['a[2]', 'c[0]']);
// => [2, 0]
_.map(_.methodOf(object), [['a', '2'], ['c', '0']]);
// => [2, 0]Adds all own enumerable string keyed 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.
0.1.0
object(Function|Object): The destination object.
(*): Returns object.
function vowels(string) {
return _.filter(function(v) {
return /[aeiou]/i.test(v);
}, string);
}
_.mixin({ 'vowels': vowels });
_.vowels('fred');
// => ['e']
_('fred').vowels().value();
// => ['e']
_.mixin([{ 'vowels': vowels }, { 'chain': false }]);
_('fred').vowels();
// => ['e']Reverts the _ variable to its previous value and returns a reference to
the lodash function.
0.1.0
(Function): Returns the lodash function.
var lodash = _.noConflict(null);A method that returns undefined.
2.3.0
_.times(_.noop, 2);
// => [undefined, undefined]Creates a function that gets the argument at index n. If n is negative,
the nth argument from the end is returned.
4.0.0
n(number): The index of the argument to return.
(Function): Returns the new pass-thru function.
var func = _.nthArg(1);
func('a', 'b', 'c', 'd');
// => 'b'
var func = _.nthArg(-2);
func('a', 'b', 'c', 'd');
// => 'c'Creates a function that invokes iteratees with the arguments it receives
and returns their results.
4.0.0
iteratees(Array|Function|Object|string)|(Array|Function|Object|string)[]): The iteratees to invoke.
(Function): Returns the new function.
var func = _.over([Math.max, Math.min]);
func(1, 2, 3, 4);
// => [4, 1]Creates a function that checks if all of the predicates return
truthy when invoked with the arguments it receives.
4.0.0
predicates(Array|Function|Object|string)|(Array|Function|Object|string)[]): The predicates to check.
(Function): Returns the new function.
var func = _.overEvery([Boolean, isFinite]);
func('1');
// => true
func(null);
// => false
func(NaN);
// => falseCreates a function that checks if any of the predicates return
truthy when invoked with the arguments it receives.
4.0.0
predicates(Array|Function|Object|string)|(Array|Function|Object|string)[]): The predicates to check.
(Function): Returns the new function.
var func = _.overSome([Boolean, isFinite]);
func('1');
// => true
func(null);
// => true
func(NaN);
// => falseCreates a function that returns the value at path of a given object.
2.4.0
path(Array|string): The path of the property to get.
(Function): Returns the new accessor function.
var objects = [
{ 'a': { 'b': 2 } },
{ 'a': { 'b': 1 } }
];
_.map(_.property('a.b'), objects);
// => [2, 1]
_.map('a.b', _.sortBy(objects, _.property(['a', 'b'])));
// => [1, 2]The opposite of _.property; this method creates a function that returns
the value at a given path of object.
3.0.0
object(Object): The object to query.
(Function): Returns the new accessor function.
var array = [0, 1, 2],
object = { 'a': array, 'b': array, 'c': array };
_.map(_.propertyOf(object), ['a[2]', 'c[0]']);
// => [2, 0]
_.map(_.propertyOf(object), [['a', '2'], ['c', '0']]);
// => [2, 0]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.
0.1.0
start(number): The start of the range.end(number): The end of the range.
(Array): Returns the range of numbers.
_.range(0, 4);
// => [0, 1, 2, 3]
_.range(0, -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, 0);
// => []This method is like _.range except that it populates values in
descending order.
4.0.0
start(number): The start of the range.end(number): The end of the range.
(Array): Returns the range of numbers.
_.rangeRight(0, 4);
// => [3, 2, 1, 0]
_.rangeRight(0, -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, 0);
// => []Create a new pristine lodash function using the context object.
1.1.0
context(Object): The context object.
(Function): Returns a new lodash function.
_.mixin({ 'foo': _.constant('foo') });
var lodash = _.runInContext(root);
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 stub `Date#getTime` use in `_.now`.
var stubbed = _.runInContext({
'Date': function() {
return { 'getTime': stubGetTime };
}
});
// Create a suped-up `defer` in Node.js.
var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;A method that returns a new empty array.
4.13.0
(Array): Returns the new empty array.
var arrays = _.times(_.stubArray, 2);
// => [[], []]
// => falseA method that returns false.
4.13.0
(boolean): Returns false.
_.times(_.stubFalse, 2);
// => [false, false]A method that returns a new empty object.
4.13.0
(Object): Returns the new empty object.
var objects = _.times(_.stubObject, 2);
// => [{}, {}]
// => falseA method that returns an empty string.
4.13.0
(string): Returns the empty string.
_.times(_.stubString, 2);
// => ['', '']A method that returns true.
4.13.0
(boolean): Returns true.
_.times(_.stubTrue, 2);
// => [true, true]Invokes the iteratee n times, returning an array of the results of
each invocation. The iteratee is invoked with one argument; (index).
0.1.0
iteratee(Function): The function invoked per iteration.n(number): The number of times to invokeiteratee.
(Array): Returns the array of results.
_.times(String, 3);
// => ['0', '1', '2']
_.times(_.constant(0), 4);
// => [0, 0, 0, 0]Converts value to a property path array.
4.0.0
value(*): The value to convert.
(Array): Returns the new property path array.
_.toPath('a.b.c');
// => ['a', 'b', 'c']
_.toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']Generates a unique ID. If prefix is given, the ID is appended to it.
0.1.0
prefix(string): The value to prefix the ID with.
(string): Returns the unique ID.
_.uniqueId('contact_');
// => 'contact_104'
_.uniqueId('');
// => '105'(string): The semantic version number.
(Object): By default, the template delimiters used by lodash are like those in embedded Ruby (ERB). Change the following template settings to use alternative delimiters.
(RegExp): Used to detect data property values to be HTML-escaped.
(RegExp): Used to detect code to be evaluated.
(Object): Used to import variables into the compiled template.
(RegExp): Used to detect data property values to inject.
(string): Used to reference the data object in the template text.
A reference to the lodash function.