diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 176a458f..00000000
--- a/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* text=auto
diff --git a/.gitignore b/.gitignore
index d4b72f29..e86fe255 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,69 @@
-.DS_Store
-.idea
-.jekyll-metadata
-.sass-cache
+# Logs
+logs
*.log
-_site
-node_modules
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+
+# nyc test coverage
+.nyc_output
+
+# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+bower_components
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (http://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules/
+jspm_packages/
+
+# Typescript v1 declaration files
+typings/
+
+# Optional npm cache directory
+.npm
+
+# Optional eslint cache
+.eslintcache
+
+# Optional REPL history
+.node_repl_history
+
+# Output of 'npm pack'
+*.tgz
+
+# dotenv environment variables file
+.env
+
+# gatsby files
+.cache/
+public
+
+# Mac files
+.DS_Store
+
+# Yarn
+yarn-error.log
+.pnp/
+.pnp.js
+# Yarn Integrity file
+.yarn-integrity
diff --git a/.nvmrc b/.nvmrc
index 7f8f011e..f20cfd99 100644
--- a/.nvmrc
+++ b/.nvmrc
@@ -1 +1 @@
-7
+10.15.1
\ No newline at end of file
diff --git a/.prettierrc b/.prettierrc
new file mode 100644
index 00000000..48e90e8d
--- /dev/null
+++ b/.prettierrc
@@ -0,0 +1,7 @@
+{
+ "endOfLine": "lf",
+ "semi": false,
+ "singleQuote": false,
+ "tabWidth": 2,
+ "trailingComma": "es5"
+}
diff --git a/404.html b/404.html
deleted file mode 100644
index 5ecd87d0..00000000
--- a/404.html
+++ /dev/null
@@ -1,11 +0,0 @@
----
-id: not-found
-title: Lodash Β· Page not found
-layout: default
----
-
- Well this is somewhat embarrassing, isnβt it? You may have been looking for our contributing guidelines, release notes, or wiki.404 Β· Page not found
-
+
+
+
+
Custom builds make it easy to create lightweight versions of Lodash containing only the features you need. To top it off, we handle all function dependency & alias mapping for you. Review the build differences & pick the one thatβs right for you.
-The Lodash command-line interface is available when lodash-cli
is installed as a global package:
- {% raw %}
-
$ npm i -g npm$ npm i -g lodash-cli$ lodash -h
core
modifier.
- {% raw %}
- lodash core
strict
modifier.
- {% raw %}
- lodash strict
modularize
modifier.
- {% raw %}
- lodash modularize
category
command to pass comma separated categories of functions to include in the build. Valid categories are βarrayβ, βcollectionβ, βdateβ, βfunctionβ, βlangβ, βobjectβ, βnumberβ, βseqβ, βstringβ, & βutilβ.
- {% raw %}
- lodash category=collection,function
exports
command to pass comma separated names of ways to export the lodash
function. Valid exports are βamdβ, βcommonjsβ, βesβ, βglobalβ, βnodeβ, βnpmβ, βnoneβ, & βumdβ.
- {% raw %}
- lodash exports=amd,node
iife
command to specify code to replace the IIFE that wraps Lodash.
- {% raw %}
- lodash iife="\!function(window,undefined){%output%}(this)"
include
command to pass comma separated names of functions to include in the build.
- {% raw %}
- lodash include=each,filter,map
minus
command to pass comma separated function/category names to remove from the build.
- {% raw %}
- lodash minus=result,shuffle
plus
command to pass comma separated function/category names to add to the build.
- {% raw %}
- lodash category=array plus=random,template
template
command to pass the file path pattern used to match template files to precompile. Note: Precompiled templates are assigned to the _.templates
object.
- {% raw %}
- lodash template="./*.jst"
settings
command to pass template settings used when precompiling templates.
- {% raw %}
- lodash settings="{interpolate:/\{\{([sS]+?)\}\}/g}"
moduleId
command to specify the AMD module ID for Lodash or the module ID used to include Lodash in compiled templates. Use βnoneβ as the module ID to create compiled templates without a dependency on Lodash.
- {% raw %}
- lodash moduleId=underscore
exports
values βesβ & βnpmβ may only be used in conjunction with the modularize
commandmodularize
command uses the first exports
values as its module format, ignoring subsequent values-o
or --output
all files created are saved to the current working directoryThe following options are also supported:
--c
, --stdout
................ Write output to standard output-d
, --development
..... Write only the non-minified development output-h
, --help
.................... Display help information-m
, --source-map
....... Generate a source map using an optional source map URL-o
, --output
................ Write output to a given path/filename-p
, --production
....... Write only the minified production output-s
, --silent
............... Skip status updates normally logged to the console-V
, --version
............. Output current version of LodashArrays
_.compact
_.difference
_.drop
-> rest
_.findIndex
_.findLastIndex
_.first
_.flatten
_.head
-> first
_.indexOf
_.initial
_.intersection
_.last
_.lastIndexOf
_.object
-> zipObject
_.pull
_.range
_.remove
_.rest
_.sortedIndex
_.tail
-> rest
_.take
-> first
_.union
_.uniq
_.unique
-> uniq
_.unzip
-> zip
_.without
_.xor
_.zip
_.zipObject
Chaining
Collections
_.all
-> every
_.any
-> some
_.at
_.collect
-> map
_.contains
_.countBy
_.detect
-> find
_.each
-> forEach
_.eachRight
-> forEachRight
_.every
_.filter
_.find
_.findLast
_.findWhere
-> find
_.foldl
-> reduce
_.foldr
-> reduceRight
_.forEach
_.forEachRight
_.groupBy
_.include
-> contains
_.indexBy
_.inject
-> reduce
_.invoke
_.map
_.max
_.min
_.pluck
_.reduce
_.reduceRight
_.reject
_.sample
_.select
-> filter
_.shuffle
_.size
_.some
_.sortBy
_.toArray
_.where
Functions
Objects
_.assign
_.clone
_.cloneDeep
_.create
_.defaults
_.extend
-> assign
_.findKey
_.findLastKey
_.forIn
_.forInRight
_.forOwn
_.forOwnRight
_.functions
_.has
_.invert
_.isArguments
_.isArray
_.isBoolean
_.isDate
_.isElement
_.isEmpty
_.isEqual
_.isFinite
_.isFunction
_.isNaN
_.isNull
_.isNumber
_.isObject
_.isPlainObject
_.isRegExp
_.isString
_.isUndefined
_.keys
_.mapValues
_.merge
_.methods
-> functions
_.omit
_.pairs
_.pick
_.transform
_.values
Utilities
Properties
_.VERSION
_.support
_.support.argsClass
_.support.argsObject
_.support.enumErrorProps
_.support.enumPrototypes
_.support.funcDecomp
_.support.funcNames
_.support.nonEnumArgs
_.support.nonEnumShadows
_.support.ownLast
_.support.spliceObjects
_.support.unindexedChars
_.templateSettings
_.templateSettings.escape
_.templateSettings.evaluate
_.templateSettings.imports
_.templateSettings.imports._
_.templateSettings.interpolate
_.templateSettings.variable
“Arrays” Methods
_.compact(array)
Creates an array with all falsey values removed. The values false
, null
,
-0
, ""
, undefined
, and NaN
are all falsey.
array
(Array): The array to compact.(Array): Returns a new array of filtered values.
-_.compact([0, 1, false, 2, '', 3]);// => [1, 2, 3]
_.difference(array, [values])
Creates an array excluding all values of the provided arrays using strict
-equality for comparisons, i.e. ===
.
array
(Array): The array to process.[values]
(...Array): The arrays of values to exclude.(Array): Returns a new array of filtered values.
-_.difference([1, 2, 3, 4, 5], [5, 2, 10]);// => [1, 3, 4]
_.findIndex(array, [callback=identity], [thisArg])
This method is like _.find
except that it returns the index of the first
-element that passes the callback check, instead of the element itself.
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(number): Returns the index of the found element, else -1
.
var characters = [ { 'name': 'barney', 'age': 36, 'blocked': false }, { 'name': 'fred', 'age': 40, 'blocked': true }, { 'name': 'pebbles', 'age': 1, 'blocked': false }]; _.findIndex(characters, function(chr) { return chr.age < 20;});// => 2 // using "_.where" callback shorthand_.findIndex(characters, { 'age': 36 });// => 0 // using "_.pluck" callback shorthand_.findIndex(characters, 'blocked');// => 1
_.findLastIndex(array, [callback=identity], [thisArg])
This method is like _.findIndex
except that it iterates over elements
-of a collection
from right to left.
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(number): Returns the index of the found element, else -1
.
var characters = [ { 'name': 'barney', 'age': 36, 'blocked': true }, { 'name': 'fred', 'age': 40, 'blocked': false }, { 'name': 'pebbles', 'age': 1, 'blocked': true }]; _.findLastIndex(characters, function(chr) { return chr.age > 30;});// => 1 // using "_.where" callback shorthand_.findLastIndex(characters, { 'age': 36 });// => 0 // using "_.pluck" callback shorthand_.findLastIndex(characters, 'blocked');// => 2
_.first(array, [callback], [thisArg])
Gets the first element or first n
elements of an array. If a callback
-is provided elements at the beginning of the array are returned as long
-as the callback returns truey. The callback is bound to thisArg
and
-invoked with three arguments; (value, index, array).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.head, _.take
-array
(Array): The array to query.[callback]
(Function|Object|number|string): The function called per element or the number of elements to return. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the first element(s) of array
.
_.first([1, 2, 3]);// => 1 _.first([1, 2, 3], 2);// => [1, 2] _.first([1, 2, 3], function(num) { return num < 3;});// => [1, 2] var characters = [ { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]; // using "_.pluck" callback shorthand_.first(characters, 'blocked');// => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] // using "_.where" callback shorthand_.pluck(_.first(characters, { 'employer': 'slate' }), 'name');// => ['barney', 'fred']
_.flatten(array, [isShallow=false], [callback=identity], [thisArg])
Flattens a nested array (the nesting can be to any depth). If isShallow
-is truey, the array will only be flattened a single level. If a callback
-is provided each element of the array is passed through the callback before
-flattening. The callback is bound to thisArg
and invoked with three
-arguments; (value, index, array).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to flatten.[isShallow=false]
(boolean): A flag to restrict flattening to a single level.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a new flattened array.
-_.flatten([1, [2], [3, [[4]]]]);// => [1, 2, 3, 4]; _.flatten([1, [2], [3, [[4]]]], true);// => [1, 2, 3, [[4]]]; var characters = [ { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]; // using "_.pluck" callback shorthand_.flatten(characters, 'pets');// => ['hoppy', 'baby puss', 'dino']
_.indexOf(array, value, [fromIndex=0])
Gets the index at which the first occurrence of value
is found using
-strict equality for comparisons, i.e. ===
. If the array is already sorted
-providing true
for fromIndex
will run a faster binary search.
array
(Array): The array to search.value
(*): The value to search for.[fromIndex=0]
(boolean|number): The index to search from or true
to perform a binary search on a sorted array.(number): Returns the index of the matched value or -1
.
_.indexOf([1, 2, 3, 1, 2, 3], 2);// => 1 _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);// => 4 _.indexOf([1, 1, 2, 2, 3, 3], 2, true);// => 2
_.initial(array, [callback=1], [thisArg])
Gets all but the last element or last n
elements of an array. If a
-callback is provided elements at the end of the array are excluded from
-the result as long as the callback returns truey. The callback is bound
-to thisArg
and invoked with three arguments; (value, index, array).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to query.[callback=1]
(Function|Object|number|string): The function called per element or the number of elements to exclude. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a slice of array
.
_.initial([1, 2, 3]);// => [1, 2] _.initial([1, 2, 3], 2);// => [1] _.initial([1, 2, 3], function(num) { return num > 1;});// => [1] var characters = [ { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]; // using "_.pluck" callback shorthand_.initial(characters, 'blocked');// => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] // using "_.where" callback shorthand_.pluck(_.initial(characters, { 'employer': 'na' }), 'name');// => ['barney', 'fred']
_.intersection([array])
Creates an array of unique values present in all provided arrays using
-strict equality for comparisons, i.e. ===
.
[array]
(...Array): The arrays to inspect.(Array): Returns an array of shared values.
-_.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);// => [1, 2]
_.last(array, [callback], [thisArg])
Gets the last element or last n
elements of an array. If a callback is
-provided elements at the end of the array are returned as long as the
-callback returns truey. The callback is bound to thisArg
and invoked
-with three arguments; (value, index, array).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to query.[callback]
(Function|Object|number|string): The function called per element or the number of elements to return. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the last element(s) of array
.
_.last([1, 2, 3]);// => 3 _.last([1, 2, 3], 2);// => [2, 3] _.last([1, 2, 3], function(num) { return num > 1;});// => [2, 3] var characters = [ { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]; // using "_.pluck" callback shorthand_.pluck(_.last(characters, 'blocked'), 'name');// => ['fred', 'pebbles'] // using "_.where" callback shorthand_.last(characters, { 'employer': 'na' });// => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
_.lastIndexOf(array, value, [fromIndex=array.length-1])
Gets the index at which the last occurrence of value
is found using strict
-equality for comparisons, i.e. ===
. If fromIndex
is negative, it is used
-as the offset from the end of the collection.
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to search.value
(*): The value to search for.[fromIndex=array.length-1]
(number): The index to search from.(number): Returns the index of the matched value or -1
.
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);// => 4 _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);// => 1
_.pull(array, [value])
Removes all provided values from the given array using strict equality for
-comparisons, i.e. ===
.
array
(Array): The array to modify.[value]
(...*): The values to remove.(Array): Returns array
.
var array = [1, 2, 3, 1, 2, 3];_.pull(array, 2, 3);console.log(array);// => [1, 1]
_.range([start=0], end, [step=1])
Creates an array of numbers (positive and/or negative) progressing from
-start
up to but not including end
. If start
is less than stop
a
-zero-length range is created unless a negative step
is specified.
[start=0]
(number): The start of the range.end
(number): The end of the range.[step=1]
(number): The value to increment or decrement by.(Array): Returns a new range array.
-_.range(4);// => [0, 1, 2, 3] _.range(1, 5);// => [1, 2, 3, 4] _.range(0, 20, 5);// => [0, 5, 10, 15] _.range(0, -4, -1);// => [0, -1, -2, -3] _.range(1, 4, 0);// => [1, 1, 1] _.range(0);// => []
_.remove(array, [callback=identity], [thisArg])
Removes all elements from an array that the callback returns truey for
-and returns an array of removed elements. The callback is bound to thisArg
-and invoked with three arguments; (value, index, array).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to modify.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a new array of removed elements.
-var array = [1, 2, 3, 4, 5, 6];var evens = _.remove(array, function(num) { return num % 2 == 0; }); console.log(array);// => [1, 3, 5] console.log(evens);// => [2, 4, 6]
_.rest(array, [callback=1], [thisArg])
The opposite of _.initial
this method gets all but the first element or
-first n
elements of an array. If a callback function is provided elements
-at the beginning of the array are excluded from the result as long as the
-callback returns truey. The callback is bound to thisArg
and invoked
-with three arguments; (value, index, array).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.drop, _.tail
-array
(Array): The array to query.[callback=1]
(Function|Object|number|string): The function called per element or the number of elements to exclude. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a slice of array
.
_.rest([1, 2, 3]);// => [2, 3] _.rest([1, 2, 3], 2);// => [3] _.rest([1, 2, 3], function(num) { return num < 3;});// => [3] var characters = [ { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]; // using "_.pluck" callback shorthand_.pluck(_.rest(characters, 'blocked'), 'name');// => ['fred', 'pebbles'] // using "_.where" callback shorthand_.rest(characters, { 'employer': 'slate' });// => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
_.sortedIndex(array, value, [callback=identity], [thisArg])
Uses a binary search to determine the smallest index at which a value
-should be inserted into a given sorted array in order to maintain the sort
-order of the array. If a callback is provided it will be executed for
-value
and each element of array
to compute their sort ranking. The
-callback is bound to thisArg
and invoked with one argument; (value).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
array
(Array): The array to inspect.value
(*): The value to evaluate.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(number): Returns the index at which value
should be inserted into array
.
_.sortedIndex([20, 30, 50], 40);// => 2 // using "_.pluck" callback shorthand_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');// => 2 var dict = { 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }}; _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { return dict.wordToNumber[word];});// => 2 _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { return this.wordToNumber[word];}, dict);// => 2
_.union([array])
Creates an array of unique values, in order, of the provided arrays using
-strict equality for comparisons, i.e. ===
.
[array]
(...Array): The arrays to inspect.(Array): Returns an array of combined values.
-_.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);// => [1, 2, 3, 5, 4]
_.uniq(array, [isSorted=false], [callback=identity], [thisArg])
Creates a duplicate-value-free version of an array using strict equality
-for comparisons, i.e. ===
. If the array is sorted, providing
-true
for isSorted
will use a faster algorithm. If a callback is provided
-each element of array
is passed through the callback before uniqueness
-is computed. The callback is bound to thisArg
and invoked with three
-arguments; (value, index, array).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.unique
-array
(Array): The array to process.[isSorted=false]
(boolean): A flag to indicate that array
is sorted.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a duplicate-value-free array.
-_.uniq([1, 2, 1, 3, 1]);// => [1, 2, 3] _.uniq([1, 1, 2, 2, 3], true);// => [1, 2, 3] _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });// => ['A', 'b', 'C'] _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);// => [1, 2.5, 3] // using "_.pluck" callback shorthand_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }, { 'x': 2 }]
_.without(array, [value])
Creates an array excluding all provided values using strict equality for
-comparisons, i.e. ===
.
array
(Array): The array to filter.[value]
(...*): The values to exclude.(Array): Returns a new array of filtered values.
-_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);// => [2, 3, 4]
_.xor([array])
Creates an array that is the symmetric difference of the provided arrays. -See http://en.wikipedia.org/wiki/Symmetric_difference.
-[array]
(...Array): The arrays to inspect.(Array): Returns an array of values.
-_.xor([1, 2, 3], [5, 2, 1, 4]);// => [3, 5, 4] _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);// => [1, 4, 5]
_.zip([array])
Creates an array of grouped elements, the first of which contains the first -elements of the given arrays, the second of which contains the second -elements of the given arrays, and so on.
-_.unzip
-[array]
(...Array): Arrays to process.(Array): Returns a new array of grouped elements.
-_.zip(['fred', 'barney'], [30, 40], [true, false]);// => [['fred', 30, true], ['barney', 40, false]]
_.zipObject(keys, [values=[]])
Creates an object composed from arrays of keys
and values
. Provide
-either a single two dimensional array, i.e. [[key1, value1], [key2, value2]]
-or two arrays, one of keys
and one of corresponding values
.
_.object
-keys
(Array): The array of keys.[values=[]]
(Array): The array of values.(Object): Returns an object composed of the given keys and corresponding values.
-_.zipObject(['fred', 'barney'], [30, 40]);// => { 'fred': 30, 'barney': 40 }
“Chaining” Methods
_(value)
Creates a lodash
object which wraps the given value to enable intuitive
-method chaining.
-
-
-In addition to Lo-Dash methods, wrappers also have the following Array
methods:
-concat
, join
, pop
, push
, reverse
, shift
, slice
, sort
, splice
,
-and unshift
-
-
-Chaining is supported in custom builds as long as the value
method is
-implicitly or explicitly included in the build.
-
-
-The chainable wrapper functions are:
-after
, assign
, bind
, bindAll
, bindKey
, chain
, compact
,
-compose
, concat
, countBy
, create
, createCallback
, curry
,
-debounce
, defaults
, defer
, delay
, difference
, filter
, flatten
,
-forEach
, forEachRight
, forIn
, forInRight
, forOwn
, forOwnRight
,
-functions
, groupBy
, indexBy
, initial
, intersection
, invert
,
-invoke
, keys
, map
, max
, memoize
, merge
, min
, object
, omit
,
-once
, pairs
, partial
, partialRight
, pick
, pluck
, pull
, push
,
-range
, reject
, remove
, rest
, reverse
, shuffle
, slice
, sort
,
-sortBy
, splice
, tap
, throttle
, times
, toArray
, transform
,
-union
, uniq
, unshift
, unzip
, values
, where
, without
, wrap
,
-and zip
-
-
-The non-chainable wrapper functions are:
-clone
, cloneDeep
, contains
, escape
, every
, find
, findIndex
,
-findKey
, findLast
, findLastIndex
, findLastKey
, has
, identity
,
-indexOf
, isArguments
, isArray
, isBoolean
, isDate
, isElement
,
-isEmpty
, isEqual
, isFinite
, isFunction
, isNaN
, isNull
, isNumber
,
-isObject
, isPlainObject
, isRegExp
, isString
, isUndefined
, join
,
-lastIndexOf
, mixin
, noConflict
, parseInt
, pop
, random
, reduce
,
-reduceRight
, result
, shift
, size
, some
, sortedIndex
, runInContext
,
-template
, unescape
, uniqueId
, and value
-
-
-The wrapper functions first
and last
return wrapped values when n
is
-provided, otherwise they return unwrapped values.
-
-
-Explicit chaining can be enabled by using the _.chain
method.
value
(*): The value to wrap in a lodash
instance.(Object): Returns a lodash
instance.
var wrapped = _([1, 2, 3]); // returns an unwrapped valuewrapped.reduce(function(sum, num) { return sum + num;});// => 6 // returns a wrapped valuevar squares = wrapped.map(function(num) { return num * num;}); _.isArray(squares);// => false _.isArray(squares.value());// => true
_.chain(value)
Creates a lodash
object that wraps the given value with explicit
-method chaining enabled.
value
(*): The value to wrap.(Object): Returns the wrapper object.
-var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }, { 'name': 'pebbles', 'age': 1 }]; var youngest = _.chain(characters) .sortBy('age') .map(function(chr) { return chr.name + ' is ' + chr.age; }) .first() .value();// => 'pebbles is 1'
_.tap(value, interceptor)
Invokes interceptor
with the value
as the first argument and then
-returns value
. The purpose of this method is to "tap into" a method
-chain in order to perform operations on intermediate results within
-the chain.
value
(*): The value to provide to interceptor
.interceptor
(Function): The function to invoke.(*): Returns value
.
_([1, 2, 3, 4]) .tap(function(array) { array.pop(); }) .reverse() .value();// => [3, 2, 1]
_.prototype.chain()
Enables explicit method chaining on the wrapper object.
-(*): Returns the wrapper object.
-var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; // without explicit chaining_(characters).first();// => { 'name': 'barney', 'age': 36 } // with explicit chaining_(characters).chain() .first() .pick('age') .value();// => { 'age': 36 }
_.prototype.toString()
Produces the toString
result of the wrapped value.
(string): Returns the string result.
-_([1, 2, 3]).toString();// => '1,2,3'
“Collections” Methods
_.at(collection, [index])
Creates an array of elements from the specified indexes, or keys, of the
-collection
. Indexes may be specified as individual arguments or as arrays
-of indexes.
collection
(Array|Object|string): The collection to iterate over.[index]
(...(number|number[]|string|string[])): The indexes of collection
to retrieve, specified as individual indexes or arrays of indexes.(Array): Returns a new array of elements corresponding to the provided indexes.
-_.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);// => ['a', 'c', 'e'] _.at(['fred', 'barney', 'pebbles'], 0, 2);// => ['fred', 'pebbles']
_.contains(collection, target, [fromIndex=0])
Checks if a given value is present in a collection using strict equality
-for comparisons, i.e. ===
. If fromIndex
is negative, it is used as the
-offset from the end of the collection.
_.include
-collection
(Array|Object|string): The collection to iterate over.target
(*): The value to check for.[fromIndex=0]
(number): The index to search from.(boolean): Returns true
if the target
element is found, else false
.
_.contains([1, 2, 3], 1);// => true _.contains([1, 2, 3], 1, 2);// => false _.contains({ 'name': 'fred', 'age': 40 }, 'fred');// => true _.contains('pebbles', 'eb');// => true
_.countBy(collection, [callback=identity], [thisArg])
Creates an object composed of keys generated from the results of running
-each element of collection
through the callback. The corresponding value
-of each key is the number of times the key was returned by the callback.
-The callback is bound to thisArg
and invoked with three arguments;
-(value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Object): Returns the composed aggregate object.
-_.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });// => { '4': 1, '6': 2 } _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);// => { '4': 1, '6': 2 } _.countBy(['one', 'two', 'three'], 'length');// => { '3': 2, '5': 1 }
_.every(collection, [callback=identity], [thisArg])
Checks if the given callback returns truey value for all elements of
-a collection. The callback is bound to thisArg
and invoked with three
-arguments; (value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.all
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(boolean): Returns true
if all elements passed the callback check, else false
.
_.every([true, 1, null, 'yes']);// => false var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; // using "_.pluck" callback shorthand_.every(characters, 'age');// => true // using "_.where" callback shorthand_.every(characters, { 'age': 36 });// => false
_.filter(collection, [callback=identity], [thisArg])
Iterates over elements of a collection, returning an array of all elements
-the callback returns truey for. The callback is bound to thisArg
and
-invoked with three arguments; (value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.select
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a new array of elements that passed the callback check.
-var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });// => [2, 4, 6] var characters = [ { 'name': 'barney', 'age': 36, 'blocked': false }, { 'name': 'fred', 'age': 40, 'blocked': true }]; // using "_.pluck" callback shorthand_.filter(characters, 'blocked');// => [{ 'name': 'fred', 'age': 40, 'blocked': true }] // using "_.where" callback shorthand_.filter(characters, { 'age': 36 });// => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
_.find(collection, [callback=identity], [thisArg])
Iterates over elements of a collection, returning the first element that
-the callback returns truey for. The callback is bound to thisArg
and
-invoked with three arguments; (value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.detect, _.findWhere
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the found element, else undefined
.
var characters = [ { 'name': 'barney', 'age': 36, 'blocked': false }, { 'name': 'fred', 'age': 40, 'blocked': true }, { 'name': 'pebbles', 'age': 1, 'blocked': false }]; _.find(characters, function(chr) { return chr.age < 40;});// => { 'name': 'barney', 'age': 36, 'blocked': false } // using "_.where" callback shorthand_.find(characters, { 'age': 1 });// => { 'name': 'pebbles', 'age': 1, 'blocked': false } // using "_.pluck" callback shorthand_.find(characters, 'blocked');// => { 'name': 'fred', 'age': 40, 'blocked': true }
_.findLast(collection, [callback=identity], [thisArg])
This method is like _.find
except that it iterates over elements
-of a collection
from right to left.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the found element, else undefined
.
_.findLast([1, 2, 3, 4], function(num) { return num % 2 == 1;});// => 3
_.forEach(collection, [callback=identity], [thisArg])
Iterates over elements of a collection, executing the callback for each
-element. The callback is bound to thisArg
and invoked with three arguments;
-(value, index|key, collection). Callbacks may exit iteration early by
-explicitly returning false
.
-
-
-Note: As with other "Collections" methods, objects with a length
property
-are iterated like arrays. To avoid this behavior _.forIn
or _.forOwn
-may be used for object iteration.
_.each
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): The this
binding of callback
.(*): Returns collection
.
_([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');// => logs each number and returns '1,2,3' _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });// => logs each number and returns the object (property order is not guaranteed across environments)
_.forEachRight(collection, [callback=identity], [thisArg])
This method is like _.forEach
except that it iterates over elements
-of a collection
from right to left.
_.eachRight
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): The this
binding of callback
.(*): Returns collection
.
_([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');// => logs each number from right to left and returns '3,2,1'
_.groupBy(collection, [callback=identity], [thisArg])
Creates an object composed of keys generated from the results of running
-each element of a collection through the callback. The corresponding value
-of each key is an array of the elements responsible for generating the key.
-The callback is bound to thisArg
and invoked with three arguments;
-(value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Object): Returns the composed aggregate object.
-_.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });// => { '4': [4.2], '6': [6.1, 6.4] } _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);// => { '4': [4.2], '6': [6.1, 6.4] } // using "_.pluck" callback shorthand_.groupBy(['one', 'two', 'three'], 'length');// => { '3': ['one', 'two'], '5': ['three'] }
_.indexBy(collection, [callback=identity], [thisArg])
Creates an object composed of keys generated from the results of running
-each element of the collection through the given callback. The corresponding
-value of each key is the last element responsible for generating the key.
-The callback is bound to thisArg
and invoked with three arguments;
-(value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Object): Returns the composed aggregate object.
-var keys = [ { 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 }]; _.indexBy(keys, 'dir');// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String);// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
_.invoke(collection, methodName, [arg])
Invokes the method named by methodName
on each element in the collection
-returning an array of the results of each invoked method. Additional arguments
-will be provided to each invoked method. If methodName
is a function it
-will be invoked for, and this
bound to, each element in the collection
.
collection
(Array|Object|string): The collection to iterate over.methodName
(Function|string): The name of the method to invoke or the function invoked per iteration.[arg]
(...*): Arguments to invoke the method with.(Array): Returns a new array of the results of each invoked method.
-_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');// => [[1, 5, 7], [1, 2, 3]] _.invoke([123, 456], String.prototype.split, '');// => [['1', '2', '3'], ['4', '5', '6']]
_.map(collection, [callback=identity], [thisArg])
Creates an array of values by running each element in the collection
-through the callback. The callback is bound to thisArg
and invoked with
-three arguments; (value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.collect
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a new array of the results of each callback
execution.
_.map([1, 2, 3], function(num) { return num * 3; });// => [3, 6, 9] _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });// => [3, 6, 9] (property order is not guaranteed across environments) var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; // using "_.pluck" callback shorthand_.map(characters, 'name');// => ['barney', 'fred']
_.max(collection, [callback=identity], [thisArg])
Retrieves the maximum value of a collection. If the collection is empty or
-falsey -Infinity
is returned. If a callback is provided it will be executed
-for each value in the collection to generate the criterion by which the value
-is ranked. The callback is bound to thisArg
and invoked with three
-arguments; (value, index, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the maximum value.
-_.max([4, 2, 8, 6]);// => 8 var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; _.max(characters, function(chr) { return chr.age; });// => { 'name': 'fred', 'age': 40 }; // using "_.pluck" callback shorthand_.max(characters, 'age');// => { 'name': 'fred', 'age': 40 };
_.min(collection, [callback=identity], [thisArg])
Retrieves the minimum value of a collection. If the collection is empty or
-falsey Infinity
is returned. If a callback is provided it will be executed
-for each value in the collection to generate the criterion by which the value
-is ranked. The callback is bound to thisArg
and invoked with three
-arguments; (value, index, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the minimum value.
-_.min([4, 2, 8, 6]);// => 2 var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; _.min(characters, function(chr) { return chr.age; });// => { 'name': 'barney', 'age': 36 }; // using "_.pluck" callback shorthand_.min(characters, 'age');// => { 'name': 'barney', 'age': 36 };
_.pluck(collection, property)
Retrieves the value of a specified property from all elements in the collection.
-collection
(Array|Object|string): The collection to iterate over.property
(string): The name of the property to pluck.(Array): Returns a new array of property values.
-var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; _.pluck(characters, 'name');// => ['barney', 'fred']
_.reduce(collection, [callback=identity], [accumulator], [thisArg])
Reduces a collection to a value which is the accumulated result of running
-each element in the collection through the callback, where each successive
-callback execution consumes the return value of the previous execution. If
-accumulator
is not provided the first element of the collection will be
-used as the initial accumulator
value. The callback is bound to thisArg
-and invoked with four arguments; (accumulator, value, index|key, collection).
_.foldl, _.inject
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[accumulator]
(*): Initial value of the accumulator.[thisArg]
(*): The this
binding of callback
.(*): Returns the accumulated value.
-var sum = _.reduce([1, 2, 3], function(sum, num) { return sum + num;});// => 6 var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { result[key] = num * 3; return result;}, {});// => { 'a': 3, 'b': 6, 'c': 9 }
_.reduceRight(collection, [callback=identity], [accumulator], [thisArg])
This method is like _.reduce
except that it iterates over elements
-of a collection
from right to left.
_.foldr
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function): The function called per iteration.[accumulator]
(*): Initial value of the accumulator.[thisArg]
(*): The this
binding of callback
.(*): Returns the accumulated value.
-var list = [[0, 1], [2, 3], [4, 5]];var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);// => [4, 5, 2, 3, 0, 1]
_.reject(collection, [callback=identity], [thisArg])
The opposite of _.filter
this method returns the elements of a
-collection that the callback does not return truey for.
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a new array of elements that failed the callback check.
-var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });// => [1, 3, 5] var characters = [ { 'name': 'barney', 'age': 36, 'blocked': false }, { 'name': 'fred', 'age': 40, 'blocked': true }]; // using "_.pluck" callback shorthand_.reject(characters, 'blocked');// => [{ 'name': 'barney', 'age': 36, 'blocked': false }] // using "_.where" callback shorthand_.reject(characters, { 'age': 36 });// => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
_.sample(collection, [n])
Retrieves a random element or n
random elements from a collection.
collection
(Array|Object|string): The collection to sample.[n]
(number): The number of elements to sample.(Array): Returns the random sample(s) of collection
.
_.sample([1, 2, 3, 4]);// => 2 _.sample([1, 2, 3, 4], 2);// => [3, 1]
_.shuffle(collection)
Creates an array of shuffled values, using a version of the Fisher-Yates -shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
-collection
(Array|Object|string): The collection to shuffle.(Array): Returns a new shuffled collection.
-_.shuffle([1, 2, 3, 4, 5, 6]);// => [4, 1, 6, 3, 5, 2]
_.size(collection)
Gets the size of the collection
by returning collection.length
for arrays
-and array-like objects or the number of own enumerable properties for objects.
collection
(Array|Object|string): The collection to inspect.(number): Returns collection.length
or number of own enumerable properties.
_.size([1, 2]);// => 2 _.size({ 'one': 1, 'two': 2, 'three': 3 });// => 3 _.size('pebbles');// => 7
_.some(collection, [callback=identity], [thisArg])
Checks if the callback returns a truey value for any element of a
-collection. The function returns as soon as it finds a passing value and
-does not iterate over the entire collection. The callback is bound to
-thisArg
and invoked with three arguments; (value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
_.any
-collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(boolean): Returns true
if any element passed the callback check, else false
.
_.some([null, 0, 'yes', false], Boolean);// => true var characters = [ { 'name': 'barney', 'age': 36, 'blocked': false }, { 'name': 'fred', 'age': 40, 'blocked': true }]; // using "_.pluck" callback shorthand_.some(characters, 'blocked');// => true // using "_.where" callback shorthand_.some(characters, { 'age': 1 });// => false
_.sortBy(collection, [callback=identity], [thisArg])
Creates an array of elements, sorted in ascending order by the results of
-running each element in a collection through the callback. This method
-performs a stable sort, that is, it will preserve the original sort order
-of equal elements. The callback is bound to thisArg
and invoked with
-three arguments; (value, index|key, collection).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an array of property names is provided for callback
the collection
-will be sorted by each property value.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
collection
(Array|Object|string): The collection to iterate over.[callback=identity]
(Array|Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a new array of sorted elements.
-_.sortBy([1, 2, 3], function(num) { return Math.sin(num); });// => [3, 1, 2] _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);// => [3, 1, 2] var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }, { 'name': 'barney', 'age': 26 }, { 'name': 'fred', 'age': 30 }]; // using "_.pluck" callback shorthand_.map(_.sortBy(characters, 'age'), _.values);// => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] // sorting by multiple properties_.map(_.sortBy(characters, ['name', 'age']), _.values);// = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
_.toArray(collection)
Converts the collection
to an array.
collection
(Array|Object|string): The collection to convert.(Array): Returns the new converted array.
-(function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);// => [2, 3, 4]
_.where(collection, props)
Performs a deep comparison of each element in a collection
to the given
-properties
object, returning an array of all elements that have equivalent
-property values.
collection
(Array|Object|string): The collection to iterate over.props
(Object): The object of property values to filter by.(Array): Returns a new array of elements that have the given properties.
-var characters = [ { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]; _.where(characters, { 'age': 36 });// => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] _.where(characters, { 'pets': ['dino'] });// => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
“Functions” Methods
_.after(n, func)
Creates a function that executes func
, with the this
binding and
-arguments of the created function, only after being called n
times.
n
(number): The number of times the function must be called before func
is executed.func
(Function): The function to restrict.(Function): Returns the new restricted function.
-var saves = ['profile', 'settings']; var done = _.after(saves.length, function() { console.log('Done saving!');}); _.forEach(saves, function(type) { asyncSave({ 'type': type, 'complete': done });});// => logs 'Done saving!', after all saves have completed
_.bind(func, [thisArg], [arg])
Creates a function that, when called, invokes func
with the this
-binding of thisArg
and prepends any additional bind
arguments to those
-provided to the bound function.
func
(Function): The function to bind.[thisArg]
(*): The this
binding of func
.[arg]
(...*): Arguments to be partially applied.(Function): Returns the new bound function.
-var func = function(greeting) { return greeting + ' ' + this.name;}; func = _.bind(func, { 'name': 'fred' }, 'hi');func();// => 'hi fred'
_.bindAll(object, [methodName])
Binds methods of an object to the object itself, overwriting the existing
-method. Method names may be specified as individual arguments or as arrays
-of method names. If no method names are provided all the function properties
-of object
will be bound.
object
(Object): The object to bind and assign the bound methods to.[methodName]
(...string): The object method names to bind, specified as individual method names or arrays of method names.(Object): Returns object
.
var view = { 'label': 'docs', 'onClick': function() { console.log('clicked ' + this.label); }}; _.bindAll(view);jQuery('#docs').on('click', view.onClick);// => logs 'clicked docs', when the button is clicked
_.bindKey(object, key, [arg])
Creates a function that, when called, invokes the method at object[key]
-and prepends any additional bindKey
arguments to those provided to the bound
-function. This method differs from _.bind
by allowing bound functions to
-reference methods that will be redefined or don't yet exist.
-See http://michaux.ca/articles/lazy-function-definition-pattern.
object
(Object): The object the method belongs to.key
(string): The key of the method.[arg]
(...*): Arguments to be partially applied.(Function): Returns the new bound function.
-var object = { 'name': 'fred', 'greet': function(greeting) { return greeting + ' ' + this.name; }}; var func = _.bindKey(object, 'greet', 'hi');func();// => 'hi fred' object.greet = function(greeting) { return greeting + 'ya ' + this.name + '!';}; func();// => 'hiya fred!'
_.compose([func])
Creates a function that is the composition of the provided functions,
-where each function consumes the return value of the function that follows.
-For example, composing the functions f()
, g()
, and h()
produces f(g(h()))
.
-Each function is executed with the this
binding of the composed function.
[func]
(...Function): Functions to compose.(Function): Returns the new composed function.
-var realNameMap = { 'pebbles': 'penelope'}; var format = function(name) { name = realNameMap[name.toLowerCase()] || name; return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();}; var greet = function(formatted) { return 'Hiya ' + formatted + '!';}; var welcome = _.compose(greet, format);welcome('pebbles');// => 'Hiya Penelope!'
_.curry(func, [arity=func.length])
Creates a function which accepts one or more arguments of func
that when
-invoked either executes func
returning its result, if all func
arguments
-have been provided, or returns a function that accepts one or more of the
-remaining func
arguments, and so on. The arity of func
can be specified
-if func.length
is not sufficient.
func
(Function): The function to curry.[arity=func.length]
(number): The arity of func
.(Function): Returns the new curried function.
-var curried = _.curry(function(a, b, c) { console.log(a + b + c);}); curried(1)(2)(3);// => 6 curried(1, 2)(3);// => 6 curried(1, 2, 3);// => 6
_.debounce(func, wait, [options])
Creates a function that will delay the execution of func
until after
-wait
milliseconds have elapsed since the last time it was invoked.
-Provide an options object to indicate that func
should be invoked on
-the leading and/or trailing edge of the wait
timeout. Subsequent calls
-to the debounced function will return the result of the last func
call.
-
-
-Note: If leading
and trailing
options are true
func
will be called
-on the trailing edge of the timeout only if the the debounced function is
-invoked more than once during the wait
timeout.
func
(Function): The function to debounce.wait
(number): The number of milliseconds to delay.[options]
(Object): The options object.[options.leading=false]
(boolean): Specify execution on the leading edge of the timeout.[options.maxWait]
(number): The maximum time func
is allowed to be delayed before it's called.[options.trailing=true]
(boolean): Specify execution on the trailing edge of the timeout.(Function): Returns the new debounced function.
-// avoid costly calculations while the window size is in fluxvar lazyLayout = _.debounce(calculateLayout, 150);jQuery(window).on('resize', lazyLayout); // execute `sendMail` when the click event is fired, debouncing subsequent callsjQuery('#postbox').on('click', _.debounce(sendMail, 300, { 'leading': true, 'trailing': false}); // ensure `batchLog` is executed once after 1 second of debounced callsvar source = new EventSource('/stream');source.addEventListener('message', _.debounce(batchLog, 250, { 'maxWait': 1000}, false);
_.defer(func, [arg])
Defers executing the func
function until the current call stack has cleared.
-Additional arguments will be provided to func
when it is invoked.
func
(Function): The function to defer.[arg]
(...*): Arguments to invoke the function with.(number): Returns the timer id.
-_.defer(function(text) { console.log(text); }, 'deferred');// logs 'deferred' after one or more milliseconds
_.delay(func, wait, [arg])
Executes the func
function after wait
milliseconds. Additional arguments
-will be provided to func
when it is invoked.
func
(Function): The function to delay.wait
(number): The number of milliseconds to delay execution.[arg]
(...*): Arguments to invoke the function with.(number): Returns the timer id.
-_.delay(function(text) { console.log(text); }, 1000, 'later');// => logs 'later' after one second
_.memoize(func, [resolver])
Creates a function that memoizes the result of func
. If resolver
is
-provided it will be used to determine the cache key for storing the result
-based on the arguments provided to the memoized function. By default, the
-first argument provided to the memoized function is used as the cache key.
-The func
is executed with the this
binding of the memoized function.
-The result cache is exposed as the cache
property on the memoized function.
func
(Function): The function to have its output memoized.[resolver]
(Function): A function used to resolve the cache key.(Function): Returns the new memoizing function.
-var fibonacci = _.memoize(function(n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);}); fibonacci(9)// => 34 var data = { 'fred': { 'name': 'fred', 'age': 40 }, 'pebbles': { 'name': 'pebbles', 'age': 1 }}; // modifying the result cachevar get = _.memoize(function(name) { return data[name]; }, _.identity);get('pebbles');// => { 'name': 'pebbles', 'age': 1 } get.cache.pebbles.name = 'penelope';get('pebbles');// => { 'name': 'penelope', 'age': 1 }
_.once(func)
Creates a function that is restricted to execute func
once. Repeat calls to
-the function will return the value of the first call. The func
is executed
-with the this
binding of the created function.
func
(Function): The function to restrict.(Function): Returns the new restricted function.
-var initialize = _.once(createApplication);initialize();initialize();// `initialize` executes `createApplication` once
_.partial(func, [arg])
Creates a function that, when called, invokes func
with any additional
-partial
arguments prepended to those provided to the new function. This
-method is similar to _.bind
except it does not alter the this
binding.
func
(Function): The function to partially apply arguments to.[arg]
(...*): Arguments to be partially applied.(Function): Returns the new partially applied function.
-var greet = function(greeting, name) { return greeting + ' ' + name; };var hi = _.partial(greet, 'hi');hi('fred');// => 'hi fred'
_.partialRight(func, [arg])
This method is like _.partial
except that partial
arguments are
-appended to those provided to the new function.
func
(Function): The function to partially apply arguments to.[arg]
(...*): Arguments to be partially applied.(Function): Returns the new partially applied function.
-var defaultsDeep = _.partialRight(_.merge, _.defaults); var options = { 'variable': 'data', 'imports': { 'jq': $ }}; defaultsDeep(options, _.templateSettings); options.variable// => 'data' options.imports// => { '_': _, 'jq': $ }
_.throttle(func, wait, [options])
Creates a function that, when executed, will only call the func
function
-at most once per every wait
milliseconds. Provide an options object to
-indicate that func
should be invoked on the leading and/or trailing edge
-of the wait
timeout. Subsequent calls to the throttled function will
-return the result of the last func
call.
-
-
-Note: If leading
and trailing
options are true
func
will be called
-on the trailing edge of the timeout only if the the throttled function is
-invoked more than once during the wait
timeout.
func
(Function): The function to throttle.wait
(number): The number of milliseconds to throttle executions to.[options]
(Object): The options object.[options.leading=true]
(boolean): Specify execution on the leading edge of the timeout.[options.trailing=true]
(boolean): Specify execution on the trailing edge of the timeout.(Function): Returns the new throttled function.
-// avoid excessively updating the position while scrollingvar throttled = _.throttle(updatePosition, 100);jQuery(window).on('scroll', throttled); // execute `renewToken` when the click event is fired, but not more than once every 5 minutesjQuery('.interactive').on('click', _.throttle(renewToken, 300000, { 'trailing': false}));
_.wrap(value, wrapper)
Creates a function that provides value
to the wrapper function as its
-first argument. Additional arguments provided to the function are appended
-to those provided to the wrapper function. The wrapper is executed with
-the this
binding of the created function.
value
(*): The value to wrap.wrapper
(Function): The wrapper function.(Function): Returns the new function.
-var p = _.wrap(_.escape, function(func, text) { return '<p>' + func(text) + '</p>';}); p('Fred, Wilma, & Pebbles');// => '<p>Fred, Wilma, & Pebbles</p>'
“Objects” Methods
_.assign(object, [source], [callback], [thisArg])
Assigns own enumerable properties of source object(s) to the destination
-object. Subsequent sources will overwrite property assignments of previous
-sources. If a callback is provided it will be executed to produce the
-assigned values. The callback is bound to thisArg
and invoked with two
-arguments; (objectValue, sourceValue).
_.extend
-object
(Object): The destination object.[source]
(...Object): The source objects.[callback]
(Function): The function to customize assigning values.[thisArg]
(*): The this
binding of callback
.(Object): Returns the destination object.
-_.assign({ 'name': 'fred' }, { 'employer': 'slate' });// => { 'name': 'fred', 'employer': 'slate' } var defaults = _.partialRight(_.assign, function(a, b) { return typeof a == 'undefined' ? b : a;}); var object = { 'name': 'barney' };defaults(object, { 'name': 'fred', 'employer': 'slate' });// => { 'name': 'barney', 'employer': 'slate' }
_.clone(value, [isDeep=false], [callback], [thisArg])
Creates a clone of value
. If isDeep
is true
nested objects will also
-be cloned, otherwise they will be assigned by reference. If a callback
-is provided it will be executed to produce the cloned values. If the
-callback returns undefined
cloning will be handled by the method instead.
-The callback is bound to thisArg
and invoked with one argument; (value).
value
(*): The value to clone.[isDeep=false]
(boolean): Specify a deep clone.[callback]
(Function): The function to customize cloning values.[thisArg]
(*): The this
binding of callback
.(*): Returns the cloned value.
-var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; var shallow = _.clone(characters);shallow[0] === characters[0];// => true var deep = _.clone(characters, true);deep[0] === characters[0];// => false _.mixin({ 'clone': _.partialRight(_.clone, function(value) { return _.isElement(value) ? value.cloneNode(false) : undefined; })}); var clone = _.clone(document.body);clone.childNodes.length;// => 0
_.cloneDeep(value, [callback], [thisArg])
Creates a deep clone of value
. If a callback is provided it will be
-executed to produce the cloned values. If the callback returns undefined
-cloning will be handled by the method instead. The callback is bound to
-thisArg
and invoked with one argument; (value).
-
-
-Note: This method is loosely based on the structured clone algorithm. Functions
-and DOM nodes are not cloned. The enumerable properties of arguments
objects and
-objects created by constructors other than Object
are cloned to plain Object
objects.
-See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
value
(*): The value to deep clone.[callback]
(Function): The function to customize cloning values.[thisArg]
(*): The this
binding of callback
.(*): Returns the deep cloned value.
-var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; var deep = _.cloneDeep(characters);deep[0] === characters[0];// => false var view = { 'label': 'docs', 'node': element}; var clone = _.cloneDeep(view, function(value) { return _.isElement(value) ? value.cloneNode(true) : undefined;}); clone.node == view.node;// => false
_.create(prototype, [properties])
Creates an object that inherits from the given prototype
object. If a
-properties
object is provided its own enumerable properties are assigned
-to the created object.
prototype
(Object): The object to inherit from.[properties]
(Object): The properties to assign to the object.(Object): Returns the new object.
-function Shape() { this.x = 0; this.y = 0;} function Circle() { Shape.call(this);} Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); var circle = new Circle;circle instanceof Circle;// => true circle instanceof Shape;// => true
_.defaults(object, [source])
Assigns own enumerable properties of source object(s) to the destination
-object for all destination properties that resolve to undefined
. Once a
-property is set, additional defaults of the same property will be ignored.
object
(Object): The destination object.[source]
(...Object): The source objects.(Object): Returns the destination object.
-var object = { 'name': 'barney' };_.defaults(object, { 'name': 'fred', 'employer': 'slate' });// => { 'name': 'barney', 'employer': 'slate' }
_.findKey(object, [callback=identity], [thisArg])
This method is like _.findIndex
except that it returns the key of the
-first element that passes the callback check, instead of the element itself.
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
object
(Object): The object to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the key of the found element, else undefined
.
var characters = { 'barney': { 'age': 36, 'blocked': false }, 'fred': { 'age': 40, 'blocked': true }, 'pebbles': { 'age': 1, 'blocked': false }}; _.findKey(characters, function(chr) { return chr.age < 40;});// => 'barney' (property order is not guaranteed across environments) // using "_.where" callback shorthand_.findKey(characters, { 'age': 1 });// => 'pebbles' // using "_.pluck" callback shorthand_.findKey(characters, 'blocked');// => 'fred'
_.findLastKey(object, [callback=identity], [thisArg])
This method is like _.findKey
except that it iterates over elements
-of a collection
in the opposite order.
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
object
(Object): The object to search.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(*): Returns the key of the found element, else undefined
.
var characters = { 'barney': { 'age': 36, 'blocked': true }, 'fred': { 'age': 40, 'blocked': false }, 'pebbles': { 'age': 1, 'blocked': true }}; _.findLastKey(characters, function(chr) { return chr.age < 40;});// => returns `pebbles`, assuming `_.findKey` returns `barney` // using "_.where" callback shorthand_.findLastKey(characters, { 'age': 40 });// => 'fred' // using "_.pluck" callback shorthand_.findLastKey(characters, 'blocked');// => 'pebbles'
_.forIn(object, [callback=identity], [thisArg])
Iterates over own and inherited enumerable properties of an object,
-executing the callback for each property. The callback is bound to thisArg
-and invoked with three arguments; (value, key, object). Callbacks may exit
-iteration early by explicitly returning false
.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): The this
binding of callback
.(Object): Returns object
.
function Shape() { this.x = 0; this.y = 0;} Shape.prototype.move = function(x, y) { this.x += x; this.y += y;}; _.forIn(new Shape, function(value, key) { console.log(key);});// => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
_.forInRight(object, [callback=identity], [thisArg])
This method is like _.forIn
except that it iterates over elements
-of a collection
in the opposite order.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): The this
binding of callback
.(Object): Returns object
.
function Shape() { this.x = 0; this.y = 0;} Shape.prototype.move = function(x, y) { this.x += x; this.y += y;}; _.forInRight(new Shape, function(value, key) { console.log(key);});// => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
_.forOwn(object, [callback=identity], [thisArg])
Iterates over own enumerable properties of an object, executing the callback
-for each property. The callback is bound to thisArg
and invoked with three
-arguments; (value, key, object). Callbacks may exit iteration early by
-explicitly returning false
.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): The this
binding of callback
.(Object): Returns object
.
_.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { console.log(key);});// => logs '0', '1', and 'length' (property order is not guaranteed across environments)
_.forOwnRight(object, [callback=identity], [thisArg])
This method is like _.forOwn
except that it iterates over elements
-of a collection
in the opposite order.
object
(Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[thisArg]
(*): The this
binding of callback
.(Object): Returns object
.
_.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { console.log(key);});// => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
_.functions(object)
Creates a sorted array of property names of all enumerable properties,
-own and inherited, of object
that have function values.
_.methods
-object
(Object): The object to inspect.(Array): Returns an array of property names that have function values.
-_.functions(_);// => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
_.has(object, key)
Checks if the specified property name exists as a direct property of object
,
-instead of an inherited property.
object
(Object): The object to inspect.key
(string): The name of the property to check.(boolean): Returns true
if key is a direct property, else false
.
_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');// => true
_.invert(object)
Creates an object composed of the inverted keys and values of the given object.
-object
(Object): The object to invert.(Object): Returns the created inverted object.
-_.invert({ 'first': 'fred', 'second': 'barney' });// => { 'fred': 'first', 'barney': 'second' }
_.isArguments(value)
Checks if value
is an arguments
object.
value
(*): The value to check.(boolean): Returns true
if the value
is an arguments
object, else false
.
(function() { return _.isArguments(arguments); })(1, 2, 3);// => true _.isArguments([1, 2, 3]);// => false
_.isArray(value)
Checks if value
is an array.
value
(*): The value to check.(boolean): Returns true
if the value
is an array, else false
.
(function() { return _.isArray(arguments); })();// => false _.isArray([1, 2, 3]);// => true
_.isBoolean(value)
Checks if value
is a boolean value.
value
(*): The value to check.(boolean): Returns true
if the value
is a boolean value, else false
.
_.isBoolean(null);// => false
_.isDate(value)
Checks if value
is a date.
value
(*): The value to check.(boolean): Returns true
if the value
is a date, else false
.
_.isDate(new Date);// => true
_.isElement(value)
Checks if value
is a DOM element.
value
(*): The value to check.(boolean): Returns true
if the value
is a DOM element, else false
.
_.isElement(document.body);// => true
_.isEmpty(value)
Checks if value
is empty. Arrays, strings, or arguments
objects with a
-length of 0
and objects with no own enumerable properties are considered
-"empty".
value
(Array|Object|string): The value to inspect.(boolean): Returns true
if the value
is empty, else false
.
_.isEmpty([1, 2, 3]);// => false _.isEmpty({});// => true _.isEmpty('');// => true
_.isEqual(a, b, [callback], [thisArg])
Performs a deep comparison between two values to determine if they are
-equivalent to each other. If a callback is provided it will be executed
-to compare values. If the callback returns undefined
comparisons will
-be handled by the method instead. The callback is bound to thisArg
and
-invoked with two arguments; (a, b).
a
(*): The value to compare.b
(*): The other value to compare.[callback]
(Function): The function to customize comparing values.[thisArg]
(*): The this
binding of callback
.(boolean): Returns true
if the values are equivalent, else false
.
var object = { 'name': 'fred' };var copy = { 'name': 'fred' }; object == copy;// => false _.isEqual(object, copy);// => true var words = ['hello', 'goodbye'];var otherWords = ['hi', 'goodbye']; _.isEqual(words, otherWords, function(a, b) { var reGreet = /^(?:hello|hi)$/i, aGreet = _.isString(a) && reGreet.test(a), bGreet = _.isString(b) && reGreet.test(b); return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;});// => true
_.isFinite(value)
Checks if value
is, or can be coerced to, a finite number.
-
-
-Note: This is not the same as native isFinite
which will return true for
-booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
value
(*): The value to check.(boolean): Returns true
if the value
is finite, else false
.
_.isFinite(-101);// => true _.isFinite('10');// => true _.isFinite(true);// => false _.isFinite('');// => false _.isFinite(Infinity);// => false
_.isFunction(value)
Checks if value
is a function.
value
(*): The value to check.(boolean): Returns true
if the value
is a function, else false
.
_.isFunction(_);// => true
_.isNaN(value)
Checks if value
is NaN
.
-
-
-Note: This is not the same as native isNaN
which will return true
for
-undefined
and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
value
(*): The value to check.(boolean): Returns true
if the value
is NaN
, else false
.
_.isNaN(NaN);// => true _.isNaN(new Number(NaN));// => true isNaN(undefined);// => true _.isNaN(undefined);// => false
_.isNull(value)
Checks if value
is null
.
value
(*): The value to check.(boolean): Returns true
if the value
is null
, else false
.
_.isNull(null);// => true _.isNull(undefined);// => false
_.isNumber(value)
Checks if value
is a number.
-
-
-Note: NaN
is considered a number. See http://es5.github.io/#x8.5.
value
(*): The value to check.(boolean): Returns true
if the value
is a number, else false
.
_.isNumber(8.4 * 5);// => true
_.isObject(value)
Checks if value
is the language type of Object.
-(e.g. arrays, functions, objects, regexes, new Number(0)
, and new String('')
)
value
(*): The value to check.(boolean): Returns true
if the value
is an object, else false
.
_.isObject({});// => true _.isObject([1, 2, 3]);// => true _.isObject(1);// => false
_.isPlainObject(value)
Checks if value
is an object created by the Object
constructor.
value
(*): The value to check.(boolean): Returns true
if value
is a plain object, else false
.
function Shape() { this.x = 0; this.y = 0;} _.isPlainObject(new Shape);// => false _.isPlainObject([1, 2, 3]);// => false _.isPlainObject({ 'x': 0, 'y': 0 });// => true
_.isRegExp(value)
Checks if value
is a regular expression.
value
(*): The value to check.(boolean): Returns true
if the value
is a regular expression, else false
.
_.isRegExp(/fred/);// => true
_.isString(value)
Checks if value
is a string.
value
(*): The value to check.(boolean): Returns true
if the value
is a string, else false
.
_.isString('fred');// => true
_.isUndefined(value)
Checks if value
is undefined
.
value
(*): The value to check.(boolean): Returns true
if the value
is undefined
, else false
.
_.isUndefined(void 0);// => true
_.keys(object)
Creates an array composed of the own enumerable property names of an object.
-object
(Object): The object to inspect.(Array): Returns an array of property names.
-_.keys({ 'one': 1, 'two': 2, 'three': 3 });// => ['one', 'two', 'three'] (property order is not guaranteed across environments)
_.mapValues(object, [callback=identity], [thisArg])
Creates an object with the same keys as object
and values generated by
-running each own enumerable property of object
through the callback.
-The callback is bound to thisArg
and invoked with three arguments;
-(value, key, object).
-
-
-If a property name is provided for callback
the created ".pluck" style
-callback will return the property value of the given element.
-
-
-If an object is provided for callback
the created ".where" style callback
-will return true
for elements that have the properties of the given object,
-else false
.
object
(Object): The object to iterate over.[callback=identity]
(Function|Object|string): The function called per iteration. If a property name or object is provided it will be used to create a ".pluck" or ".where" style callback, respectively.[thisArg]
(*): The this
binding of callback
.(Array): Returns a new object with values of the results of each callback
execution.
_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });// => { 'a': 3, 'b': 6, 'c': 9 } var characters = { 'fred': { 'name': 'fred', 'age': 40 }, 'pebbles': { 'name': 'pebbles', 'age': 1 }}; // using "_.pluck" callback shorthand_.mapValues(characters, 'age');// => { 'fred': 40, 'pebbles': 1 }
_.merge(object, [source], [callback], [thisArg])
Recursively merges own enumerable properties of the source object(s), that
-don't resolve to undefined
into the destination object. Subsequent sources
-will overwrite property assignments of previous sources. If a callback is
-provided it will be executed to produce the merged values of the destination
-and source properties. If the callback returns undefined
merging will
-be handled by the method instead. The callback is bound to thisArg
and
-invoked with two arguments; (objectValue, sourceValue).
object
(Object): The destination object.[source]
(...Object): The source objects.[callback]
(Function): The function to customize merging properties.[thisArg]
(*): The this
binding of callback
.(Object): Returns the destination object.
-var names = { 'characters': [ { 'name': 'barney' }, { 'name': 'fred' } ]}; var ages = { 'characters': [ { 'age': 36 }, { 'age': 40 } ]}; _.merge(names, ages);// => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } var food = { 'fruits': ['apple'], 'vegetables': ['beet']}; var otherFood = { 'fruits': ['banana'], 'vegetables': ['carrot']}; _.merge(food, otherFood, function(a, b) { return _.isArray(a) ? a.concat(b) : undefined;});// => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
_.omit(object, [callback], [thisArg])
Creates a shallow clone of object
excluding the specified properties.
-Property names may be specified as individual arguments or as arrays of
-property names. If a callback is provided it will be executed for each
-property of object
omitting the properties the callback returns truey
-for. The callback is bound to thisArg
and invoked with three arguments;
-(value, key, object).
object
(Object): The source object.[callback]
(...((string|string[])|Function)): The properties to omit or the function called per iteration.[thisArg]
(*): The this
binding of callback
.(Object): Returns an object without the omitted properties.
-_.omit({ 'name': 'fred', 'age': 40 }, 'age');// => { 'name': 'fred' } _.omit({ 'name': 'fred', 'age': 40 }, function(value) { return typeof value == 'number';});// => { 'name': 'fred' }
_.pairs(object)
Creates a two dimensional array of an object's key-value pairs,
-i.e. [[key1, value1], [key2, value2]]
.
object
(Object): The object to inspect.(Array): Returns new array of key-value pairs.
-_.pairs({ 'barney': 36, 'fred': 40 });// => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
_.pick(object, [callback], [thisArg])
Creates a shallow clone of object
composed of the specified properties.
-Property names may be specified as individual arguments or as arrays of
-property names. If a callback is provided it will be executed for each
-property of object
picking the properties the callback returns truey
-for. The callback is bound to thisArg
and invoked with three arguments;
-(value, key, object).
object
(Object): The source object.[callback]
(...((string|string[])|Function)): The function called per iteration or property names to pick, specified as individual property names or arrays of property names.[thisArg]
(*): The this
binding of callback
.(Object): Returns an object composed of the picked properties.
-_.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');// => { 'name': 'fred' } _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { return key.charAt(0) != '_';});// => { 'name': 'fred' }
_.transform(object, [callback=identity], [accumulator], [thisArg])
An alternative to _.reduce
this method transforms object
to a new
-accumulator
object which is the result of running each of its own
-enumerable properties through a callback, with each callback execution
-potentially mutating the accumulator
object. The callback is bound to
-thisArg
and invoked with four arguments; (accumulator, value, key, object).
-Callbacks may exit iteration early by explicitly returning false
.
object
(Array|Object): The object to iterate over.[callback=identity]
(Function): The function called per iteration.[accumulator]
(*): The custom accumulator value.[thisArg]
(*): The this
binding of callback
.(*): Returns the accumulated value.
-var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { num *= num; if (num % 2) { return result.push(num) < 3; }});// => [1, 9, 25] var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { result[key] = num * 3;});// => { 'a': 3, 'b': 6, 'c': 9 }
_.values(object)
Creates an array composed of the own enumerable property values of object
.
object
(Object): The object to inspect.(Array): Returns an array of property values.
-_.values({ 'one': 1, 'two': 2, 'three': 3 });// => [1, 2, 3] (property order is not guaranteed across environments)
“Utilities” Methods
_.constant(value)
Creates a function that returns value
.
value
(*): The value to return from the new function.(Function): Returns the new function.
-var object = { 'name': 'fred' };var getter = _.constant(object);getter() === object;// => true
_.createCallback([func=identity], [thisArg], [argCount])
Produces a callback bound to an optional thisArg
. If func
is a property
-name the created callback will return the property value for a given element.
-If func
is an object the created callback will return true
for elements
-that contain the equivalent object properties, otherwise it will return false
.
[func=identity]
(*): The value to convert to a callback.[thisArg]
(*): The this
binding of the created callback.[argCount]
(number): The number of arguments the callback accepts.(Function): Returns a callback function.
-var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]; // wrap to create custom callback shorthands_.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); return !match ? func(callback, thisArg) : function(object) { return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; };}); _.filter(characters, 'age__gt38');// => [{ 'name': 'fred', 'age': 40 }]
_.escape(string)
Converts the characters &
, <
, >
, "
, and '
in string
to their
-corresponding HTML entities.
string
(string): The string to escape.(string): Returns the escaped string.
-_.escape('Fred, Wilma, & Pebbles');// => 'Fred, Wilma, & Pebbles'
_.identity(value)
This method returns the first argument provided to it.
-value
(*): Any value.(*): Returns value
.
var object = { 'name': 'fred' };_.identity(object) === object;// => true
_.mixin([object=lodash], source, [options])
Adds function properties of a source object to the destination object.
-If object
is a function methods will be added to its prototype as well.
[object=lodash]
(Function|Object): object The destination object.source
(Object): The object of functions to add.[options]
(Object): The options object.[options.chain=true]
(boolean): Specify whether the functions added are chainable.function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();} _.mixin({ 'capitalize': capitalize });_.capitalize('fred');// => 'Fred' _('fred').capitalize().value();// => 'Fred' _.mixin({ 'capitalize': capitalize }, { 'chain': false });_('fred').capitalize();// => 'Fred'
_.noConflict()
Reverts the '_' variable to its previous value and returns a reference to
-the lodash
function.
(Function): Returns the lodash
function.
var lodash = _.noConflict();
_.noop()
A no-operation function.
-var object = { 'name': 'fred' };_.noop(object) === undefined;// => true
_.now
Gets the number of milliseconds that have elapsed since the Unix epoch -(1 January 1970 00:00:00 UTC).
-var stamp = _.now();_.defer(function() { console.log(_.now() - stamp); });// => logs the number of milliseconds it took for the deferred function to be called
_.parseInt(value, [radix])
Converts the given value into an integer of the specified radix.
-If radix
is undefined
or 0
a radix
of 10
is used unless the
-value
is a hexadecimal, in which case a radix
of 16
is used.
-
-
-Note: This method avoids differences in native ES3 and ES5 parseInt
-implementations. See http://es5.github.io/#E.
value
(string): The value to parse.[radix]
(number): The radix used to interpret the value to parse.(number): Returns the new integer value.
-_.parseInt('08');// => 8
_.property(key)
Creates a "_.pluck" style function, which returns the key
value of a
-given object.
key
(string): The name of the property to retrieve.(Function): Returns the new function.
-var characters = [ { 'name': 'fred', 'age': 40 }, { 'name': 'barney', 'age': 36 }]; var getName = _.property('name'); _.map(characters, getName);// => ['barney', 'fred'] _.sortBy(characters, getName);// => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
_.random([min=0], [max=1], [floating=false])
Produces a random number between min
and max
(inclusive). If only one
-argument is provided a number between 0
and the given number will be
-returned. If floating
is truey or either min
or max
are floats a
-floating-point number will be returned instead of an integer.
[min=0]
(number): The minimum possible value.[max=1]
(number): The maximum possible value.[floating=false]
(boolean): Specify returning a floating-point number.(number): Returns a random number.
-_.random(0, 5);// => an integer between 0 and 5 _.random(5);// => also an integer between 0 and 5 _.random(5, true);// => a floating-point number between 0 and 5 _.random(1.2, 5.2);// => a floating-point number between 1.2 and 5.2
_.result(object, key)
Resolves the value of property key
on object
. If key
is a function
-it will be invoked with the this
binding of object
and its result returned,
-else the property value is returned. If object
is falsey then undefined
-is returned.
object
(Object): The object to inspect.key
(string): The name of the property to resolve.(*): Returns the resolved value.
-var object = { 'cheese': 'crumpets', 'stuff': function() { return 'nonsense'; }}; _.result(object, 'cheese');// => 'crumpets' _.result(object, 'stuff');// => 'nonsense'
_.runInContext([context=root])
Create a new lodash
function using the given context object.
[context=root]
(Object): The context object.(Function): Returns the lodash
function.
_.template(text, data, [options], [sourceURL], [variable])
A micro-templating method that handles arbitrary delimiters, preserves
-whitespace, and correctly escapes quotes within interpolated code.
-
-
-Note: In the development build, _.template
utilizes sourceURLs for easier
-debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
-
-
-For more information on precompiling templates see:
-https://lodash.com/custom-builds
-
-
-For more information on Chrome extension sandboxes see:
-http://developer.chrome.com/stable/extensions/sandboxingEval.html
text
(string): The template text.data
(Object): The data object used to populate the text.[options]
(Object): The options object.[options.escape]
(RegExp): The "escape" delimiter.[options.evaluate]
(RegExp): The "evaluate" delimiter.[options.imports]
(Object): An object to import into the template as local variables.[options.interpolate]
(RegExp): The "interpolate" delimiter.[sourceURL]
(string): The sourceURL of the template's compiled source.[variable]
(string): The data object variable name.(*): Returns a compiled function when no data
object is given, else it returns the interpolated text.
// using the "interpolate" delimiter to create a compiled templatevar compiled = _.template('hello <%= name %>');compiled({ 'name': 'fred' });// => 'hello fred' // using the "escape" delimiter to escape HTML in data property values_.template('<b><%- value %></b>', { 'value': '<script>' });// => '<b><script></b>' // using the "evaluate" delimiter to generate HTMLvar list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';_.template(list, { 'people': ['fred', 'barney'] });// => '<li>fred</li><li>barney</li>' // using the ES6 delimiter as an alternative to the default "interpolate" delimiter_.template('hello ${ name }', { 'name': 'pebbles' });// => 'hello pebbles' // using the internal `print` function in "evaluate" delimiters_.template('<% print("hello " + name); %>!', { 'name': 'barney' });// => 'hello barney!' // using a custom template delimiters_.templateSettings = { 'interpolate': /{{([\s\S]+?)}}/g}; _.template('hello {{ name }}!', { 'name': 'mustache' });// => 'hello mustache!' // using the `imports` option to import jQueryvar list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';_.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });// => '<li>fred</li><li>barney</li>' // using the `sourceURL` option to specify a custom sourceURL for the templatevar compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });compiled(data);// => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector // using the `variable` option to ensure a with-statement isn't used in the compiled templatevar compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });compiled.source;// => function(data) { var __t, __p = '', __e = _.escape; __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!'; return __p;} // using the `source` property to inline compiled templates for meaningful// line numbers in error messages and a stack tracefs.writeFileSync(path.join(cwd, 'jst.js'), '\ var JST = {\ "main": ' + _.template(mainText).source + '\ };\');
_.times(n, callback, [thisArg])
Executes the callback n
times, returning an array of the results
-of each callback execution. The callback is bound to thisArg
and invoked
-with one argument; (index).
n
(number): The number of times to execute the callback.callback
(Function): The function called per iteration.[thisArg]
(*): The this
binding of callback
.(Array): Returns an array of the results of each callback
execution.
var diceRolls = _.times(3, _.partial(_.random, 1, 6));// => [3, 6, 4] _.times(3, function(n) { mage.castSpell(n); });// => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively _.times(3, function(n) { this.cast(n); }, mage);// => also calls `mage.castSpell(n)` three times
_.unescape(string)
The inverse of _.escape
this method converts the HTML entities
-&
, <
, >
, "
, and '
in string
to their
-corresponding characters.
string
(string): The string to unescape.(string): Returns the unescaped string.
-_.unescape('Fred, Barney & Pebbles');// => 'Fred, Barney & Pebbles'
Properties
_.support.argsClass
Detect if an arguments
object's [[Class]] is resolvable (all but Firefox < 4
, IE < 9
).
_.support.argsObject
Detect if arguments
objects are Object
objects (all but Narwhal and Opera < 10.5
).
_.support.enumErrorProps
Detect if name
or message
properties of Error.prototype
are
-enumerable by default. (IE < 9
, Safari < 5.1
)
_.support.enumPrototypes
Detect if prototype
properties are enumerable by default.
-
-
-Firefox < 3.6
, Opera > 9.50
- Opera < 11.60
, and Safari < 5.1
-(if the prototype or a property on the prototype has been set)
-incorrectly sets a function's prototype
property [[Enumerable]]
-value to true
.
_.support.funcDecomp
Detect if functions can be decompiled by Function#toString
-(all but PS3 and older Opera mobile browsers & avoided in Windows 8
apps).
_.support.nonEnumArgs
Detect if arguments
object indexes are non-enumerable
-(Firefox < 4
, IE < 9
, PhantomJS, Safari < 5.1
).
_.support.nonEnumShadows
Detect if properties shadowing those on Object.prototype
are non-enumerable.
-
-
-In IE < 9
an objects own properties, shadowing non-enumerable ones, are
-made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug).
_.support.ownLast
Detect if own properties are iterated after inherited properties (all but IE < 9
).
_.support.spliceObjects
Detect if Array#shift
and Array#splice
augment array-like objects correctly.
-
-
-Firefox < 10
, IE compatibility mode, and IE < 9
have buggy Array shift()
-and splice()
functions that fail to remove the last element, value[0]
,
-of array-like objects even though the length
property is set to 0
.
-The shift()
method is buggy in IE 8
compatibility mode, while splice()
-is buggy regardless of mode in IE < 9
and buggy in compatibility mode in IE 9
.
_.support.unindexedChars
Detect lack of support for accessing string characters by index.
-
-
-IE < 8
can't access characters by index and IE 8
can only access
-characters by index on string literals.
Array
_.chunk
_.compact
_.difference
_.drop
_.dropRight
_.dropRightWhile
_.dropWhile
_.fill
_.findIndex
_.findLastIndex
_.first
_.flatten
_.flattenDeep
_.head
-> first
_.indexOf
_.initial
_.intersection
_.last
_.lastIndexOf
_.object
-> zipObject
_.pull
_.pullAt
_.remove
_.rest
_.slice
_.sortedIndex
_.sortedLastIndex
_.tail
-> rest
_.take
_.takeRight
_.takeRightWhile
_.takeWhile
_.union
_.uniq
_.unique
-> uniq
_.unzip
_.unzipWith
_.without
_.xor
_.zip
_.zipObject
_.zipWith
Chain
Collections
_.all
-> every
_.any
-> some
_.at
_.collect
-> map
_.contains
-> includes
_.countBy
_.detect
-> find
_.each
-> forEach
_.eachRight
-> forEachRight
_.every
_.filter
_.find
_.findLast
_.findWhere
_.foldl
-> reduce
_.foldr
-> reduceRight
_.forEach
_.forEachRight
_.groupBy
_.include
-> includes
_.includes
_.indexBy
_.inject
-> reduce
_.invoke
_.map
_.partition
_.pluck
_.reduce
_.reduceRight
_.reject
_.sample
_.select
-> filter
_.shuffle
_.size
_.some
_.sortBy
_.sortByAll
_.sortByOrder
_.where
Date
_.now
Function
Lang
_.clone
_.cloneDeep
_.eq
-> isEqual
_.gt
_.gte
_.isArguments
_.isArray
_.isBoolean
_.isDate
_.isElement
_.isEmpty
_.isEqual
_.isError
_.isFinite
_.isFunction
_.isMatch
_.isNaN
_.isNative
_.isNull
_.isNumber
_.isObject
_.isPlainObject
_.isRegExp
_.isString
_.isTypedArray
_.isUndefined
_.lt
_.lte
_.toArray
_.toPlainObject
Object
_.assign
_.create
_.defaults
_.defaultsDeep
_.extend
-> assign
_.findKey
_.findLastKey
_.forIn
_.forInRight
_.forOwn
_.forOwnRight
_.functions
_.get
_.has
_.invert
_.keys
_.keysIn
_.mapKeys
_.mapValues
_.merge
_.methods
-> functions
_.omit
_.pairs
_.pick
_.result
_.set
_.transform
_.values
_.valuesIn
String
Utility
“Array” Methods
_.chunk(array, [size=1])
Creates an array of elements split into groups the length of size
.
-If collection
can't be split evenly, the final chunk will be the remaining
-elements.
array
(Array): The array to process.[size=1]
(number): The length of each chunk.(Array): Returns the new array containing chunks.
-_.chunk(['a', 'b', 'c', 'd'], 2);// => [['a', 'b'], ['c', 'd']] _.chunk(['a', 'b', 'c', 'd'], 3);// => [['a', 'b', 'c'], ['d']]
_.compact(array)
Creates an array with all falsey values removed. The values false
, null
,
-0
, ""
, undefined
, and NaN
are falsey.
array
(Array): The array to compact.(Array): Returns the new array of filtered values.
-_.compact([0, 1, false, 2, '', 3]);// => [1, 2, 3]
_.difference(array, [values])
Creates an array of unique array
values not included in the other
-provided arrays using SameValueZero
-for equality comparisons.
array
(Array): The array to inspect.[values]
(...Array): The arrays of values to exclude.(Array): Returns the new array of filtered values.
-_.difference([1, 2, 3], [4, 2]);// => [1, 3]
_.drop(array, [n=1])
Creates a slice of array
with n
elements dropped from the beginning.
array
(Array): The array to query.[n=1]
(number): The number of elements to drop.(Array): Returns the slice of array
.
_.drop([1, 2, 3]);// => [2, 3] _.drop([1, 2, 3], 2);// => [3] _.drop([1, 2, 3], 5);// => [] _.drop([1, 2, 3], 0);// => [1, 2, 3]
_.dropRight(array, [n=1])
Creates a slice of array
with n
elements dropped from the end.
array
(Array): The array to query.[n=1]
(number): The number of elements to drop.(Array): Returns the slice of array
.
_.dropRight([1, 2, 3]);// => [1, 2] _.dropRight([1, 2, 3], 2);// => [1] _.dropRight([1, 2, 3], 5);// => [] _.dropRight([1, 2, 3], 0);// => [1, 2, 3]
_.dropRightWhile(array, [predicate=_.identity], [thisArg])
Creates a slice of array
excluding elements dropped from the end.
-Elements are dropped until predicate
returns falsey. The predicate is
-bound to thisArg
and invoked with three arguments: (value, index, array).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that match the properties of the given
-object, else false
.
array
(Array): The array to query.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the slice of array
.
_.dropRightWhile([1, 2, 3], function(n) { return n > 1;});// => [1] var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': false }]; // using the `_.matches` callback shorthand_.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');// => ['barney', 'fred'] // using the `_.matchesProperty` callback shorthand_.pluck(_.dropRightWhile(users, 'active', false), 'user');// => ['barney'] // using the `_.property` callback shorthand_.pluck(_.dropRightWhile(users, 'active'), 'user');// => ['barney', 'fred', 'pebbles']
_.dropWhile(array, [predicate=_.identity], [thisArg])
Creates a slice of array
excluding elements dropped from the beginning.
-Elements are dropped until predicate
returns falsey. The predicate is
-bound to thisArg
and invoked with three arguments: (value, index, array).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
array
(Array): The array to query.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the slice of array
.
_.dropWhile([1, 2, 3], function(n) { return n < 3;});// => [3] var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': true }]; // using the `_.matches` callback shorthand_.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');// => ['fred', 'pebbles'] // using the `_.matchesProperty` callback shorthand_.pluck(_.dropWhile(users, 'active', false), 'user');// => ['pebbles'] // using the `_.property` callback shorthand_.pluck(_.dropWhile(users, 'active'), 'user');// => ['barney', 'fred', 'pebbles']
_.fill(array, value, [start=0], [end=array.length])
Fills elements of array
with value
from start
up to, but not
-including, end
.
-
-
-Note: This method mutates array
.
array
(Array): The array to fill.value
(*): The value to fill array
with.[start=0]
(number): The start position.[end=array.length]
(number): The end position.(Array): Returns array
.
var array = [1, 2, 3]; _.fill(array, 'a');console.log(array);// => ['a', 'a', 'a'] _.fill(Array(3), 2);// => [2, 2, 2] _.fill([4, 6, 8], '*', 1, 2);// => [4, '*', 8]
_.findIndex(array, [predicate=_.identity], [thisArg])
This method is like _.find
except that it returns the index of the first
-element predicate
returns truthy for instead of the element itself.
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
array
(Array): The array to search.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(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(users, function(chr) { return chr.user == 'barney';});// => 0 // using the `_.matches` callback shorthand_.findIndex(users, { 'user': 'fred', 'active': false });// => 1 // using the `_.matchesProperty` callback shorthand_.findIndex(users, 'active', false);// => 0 // using the `_.property` callback shorthand_.findIndex(users, 'active');// => 2
_.findLastIndex(array, [predicate=_.identity], [thisArg])
This method is like _.findIndex
except that it iterates over elements
-of collection
from right to left.
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
array
(Array): The array to search.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(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(users, function(chr) { return chr.user == 'pebbles';});// => 2 // using the `_.matches` callback shorthand_.findLastIndex(users, { 'user': 'barney', 'active': true });// => 0 // using the `_.matchesProperty` callback shorthand_.findLastIndex(users, 'active', false);// => 2 // using the `_.property` callback shorthand_.findLastIndex(users, 'active');// => 0
_.first(array)
Gets the first element of array
.
_.head
-array
(Array): The array to query.(*): Returns the first element of array
.
_.first([1, 2, 3]);// => 1 _.first([]);// => undefined
_.flatten(array, [isDeep])
Flattens a nested array. If isDeep
is true
the array is recursively
-flattened, otherwise it's only flattened a single level.
array
(Array): The array to flatten.[isDeep]
(boolean): Specify a deep flatten.(Array): Returns the new flattened array.
-_.flatten([1, [2, 3, [4]]]);// => [1, 2, 3, [4]] // using `isDeep`_.flatten([1, [2, 3, [4]]], true);// => [1, 2, 3, 4]
_.flattenDeep(array)
Recursively flattens a nested array.
-array
(Array): The array to recursively flatten.(Array): Returns the new flattened array.
-_.flattenDeep([1, [2, 3, [4]]]);// => [1, 2, 3, 4]
_.indexOf(array, value, [fromIndex=0])
Gets the index at which the first occurrence of value
is found in array
-using SameValueZero
-for equality comparisons. If fromIndex
is negative, it's used as the offset
-from the end of array
. If array
is sorted providing true
for fromIndex
-performs a faster binary search.
array
(Array): The array to search.value
(*): The value to search for.[fromIndex=0]
(boolean|number): The index to search from or true
to perform a binary search on a sorted array.(number): Returns the index of the matched value, else -1
.
_.indexOf([1, 2, 1, 2], 2);// => 1 // using `fromIndex`_.indexOf([1, 2, 1, 2], 2, 2);// => 3 // performing a binary search_.indexOf([1, 1, 2, 2], 2, true);// => 2
_.initial(array)
Gets all but the last element of array
.
array
(Array): The array to query.(Array): Returns the slice of array
.
_.initial([1, 2, 3]);// => [1, 2]
_.intersection([arrays])
Creates an array of unique values that are included in all of the provided
-arrays using SameValueZero
-for equality comparisons.
[arrays]
(...Array): The arrays to inspect.(Array): Returns the new array of shared values.
-_.intersection([1, 2], [4, 2], [2, 1]);// => [2]
_.last(array)
Gets the last element of array
.
array
(Array): The array to query.(*): Returns the last element of array
.
_.last([1, 2, 3]);// => 3
_.lastIndexOf(array, value, [fromIndex=array.length-1])
This method is like _.indexOf
except that it iterates over elements of
-array
from right to left.
array
(Array): The array to search.value
(*): The value to search for.[fromIndex=array.length-1]
(boolean|number): The index to search from or true
to perform a binary search on a sorted array.(number): Returns the index of the matched value, else -1
.
_.lastIndexOf([1, 2, 1, 2], 2);// => 3 // using `fromIndex`_.lastIndexOf([1, 2, 1, 2], 2, 2);// => 1 // performing a binary search_.lastIndexOf([1, 1, 2, 2], 2, true);// => 3
_.pull(array, [values])
Removes all provided values from array
using
-SameValueZero
-for equality comparisons.
-
-
-Note: Unlike _.without
, this method mutates array
.
array
(Array): The array to modify.[values]
(...*): The values to remove.(Array): Returns array
.
var array = [1, 2, 3, 1, 2, 3]; _.pull(array, 2, 3);console.log(array);// => [1, 1]
_.pullAt(array, [indexes])
Removes elements from array
corresponding to the given indexes and returns
-an array of the removed elements. Indexes may be specified as an array of
-indexes or as individual arguments.
-
-
-Note: Unlike _.at
, this method mutates array
.
array
(Array): The array to modify.[indexes]
(...(number|number[])): The indexes of elements to remove, specified as individual indexes or arrays of indexes.(Array): Returns the new array of removed elements.
-var array = [5, 10, 15, 20];var evens = _.pullAt(array, 1, 3); console.log(array);// => [5, 15] console.log(evens);// => [10, 20]
_.remove(array, [predicate=_.identity], [thisArg])
Removes all elements from array
that predicate
returns truthy for
-and returns an array of the removed elements. The predicate is bound to
-thisArg
and invoked with three arguments: (value, index, array).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
-
-
-Note: Unlike _.filter
, this method mutates array
.
array
(Array): The array to modify.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the new array of removed elements.
-var array = [1, 2, 3, 4];var evens = _.remove(array, function(n) { return n % 2 == 0;}); console.log(array);// => [1, 3] console.log(evens);// => [2, 4]
_.rest(array)
Gets all but the first element of array
.
_.tail
-array
(Array): The array to query.(Array): Returns the slice of array
.
_.rest([1, 2, 3]);// => [2, 3]
_.slice(array, [start=0], [end=array.length])
Creates a slice of array
from start
up to, but not including, end
.
-
-
-Note: This method is used instead of Array#slice
to support node
-lists in IE < 9
and to ensure dense arrays are returned.
array
(Array): The array to slice.[start=0]
(number): The start position.[end=array.length]
(number): The end position.(Array): Returns the slice of array
.
_.sortedIndex(array, value, [iteratee=_.identity], [thisArg])
Uses a binary search to determine the lowest index at which value
should
-be inserted into array
in order to maintain its sort order. If an iteratee
-function is provided it's invoked for value
and each element of array
-to compute their sort ranking. The iteratee is bound to thisArg
and
-invoked with one argument; (value).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
array
(Array): The sorted array to inspect.value
(*): The value to evaluate.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(number): Returns the index at which value
should be inserted into array
.
_.sortedIndex([30, 50], 40);// => 1 _.sortedIndex([4, 4, 5, 5], 5);// => 2 var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; // using an iteratee function_.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { return this.data[word];}, dict);// => 1 // using the `_.property` callback shorthand_.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');// => 1
_.sortedLastIndex(array, value, [iteratee=_.identity], [thisArg])
This method is like _.sortedIndex
except that it returns the highest
-index at which value
should be inserted into array
in order to
-maintain its sort order.
array
(Array): The sorted array to inspect.value
(*): The value to evaluate.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(number): Returns the index at which value
should be inserted into array
.
_.sortedLastIndex([4, 4, 5, 5], 5);// => 4
_.take(array, [n=1])
Creates a slice of array
with n
elements taken from the beginning.
array
(Array): The array to query.[n=1]
(number): The number of elements to take.(Array): Returns the slice of array
.
_.take([1, 2, 3]);// => [1] _.take([1, 2, 3], 2);// => [1, 2] _.take([1, 2, 3], 5);// => [1, 2, 3] _.take([1, 2, 3], 0);// => []
_.takeRight(array, [n=1])
Creates a slice of array
with n
elements taken from the end.
array
(Array): The array to query.[n=1]
(number): The number of elements to take.(Array): Returns the slice of array
.
_.takeRight([1, 2, 3]);// => [3] _.takeRight([1, 2, 3], 2);// => [2, 3] _.takeRight([1, 2, 3], 5);// => [1, 2, 3] _.takeRight([1, 2, 3], 0);// => []
_.takeRightWhile(array, [predicate=_.identity], [thisArg])
Creates a slice of array
with elements taken from the end. Elements are
-taken until predicate
returns falsey. The predicate is bound to thisArg
-and invoked with three arguments: (value, index, array).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
array
(Array): The array to query.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the slice of array
.
_.takeRightWhile([1, 2, 3], function(n) { return n > 1;});// => [2, 3] var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': false }]; // using the `_.matches` callback shorthand_.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');// => ['pebbles'] // using the `_.matchesProperty` callback shorthand_.pluck(_.takeRightWhile(users, 'active', false), 'user');// => ['fred', 'pebbles'] // using the `_.property` callback shorthand_.pluck(_.takeRightWhile(users, 'active'), 'user');// => []
_.takeWhile(array, [predicate=_.identity], [thisArg])
Creates a slice of array
with elements taken from the beginning. Elements
-are taken until predicate
returns falsey. The predicate is bound to
-thisArg
and invoked with three arguments: (value, index, array).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
array
(Array): The array to query.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the slice of array
.
_.takeWhile([1, 2, 3], function(n) { return n < 3;});// => [1, 2] var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false}, { 'user': 'pebbles', 'active': true }]; // using the `_.matches` callback shorthand_.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');// => ['barney'] // using the `_.matchesProperty` callback shorthand_.pluck(_.takeWhile(users, 'active', false), 'user');// => ['barney', 'fred'] // using the `_.property` callback shorthand_.pluck(_.takeWhile(users, 'active'), 'user');// => []
_.union([arrays])
Creates an array of unique values, in order, from all of the provided arrays
-using SameValueZero
-for equality comparisons.
[arrays]
(...Array): The arrays to inspect.(Array): Returns the new array of combined values.
-_.union([1, 2], [4, 2], [2, 1]);// => [1, 2, 4]
_.uniq(array, [isSorted], [iteratee], [thisArg])
Creates a duplicate-free version of an array, using
-SameValueZero
-for equality comparisons, in which only the first occurrence of each element
-is kept. Providing true
for isSorted
performs a faster search algorithm
-for sorted arrays. If an iteratee function is provided it's invoked for
-each element in the array to generate the criterion by which uniqueness
-is computed. The iteratee
is bound to thisArg
and invoked with three
-arguments: (value, index, array).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
_.unique
-array
(Array): The array to inspect.[isSorted]
(boolean): Specify the array is sorted.[iteratee]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Array): Returns the new duplicate-value-free array.
-_.uniq([2, 1, 2]);// => [2, 1] // using `isSorted`_.uniq([1, 1, 2], true);// => [1, 2] // using an iteratee function_.uniq([1, 2.5, 1.5, 2], function(n) { return this.floor(n);}, Math);// => [1, 2.5] // using the `_.property` callback shorthand_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }, { 'x': 2 }]
_.unzip(array)
This method is like _.zip
except that it accepts an array of grouped
-elements and creates an array regrouping the elements to their pre-zip
-configuration.
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]]
_.unzipWith(array, [iteratee], [thisArg])
This method is like _.unzip
except that it accepts an iteratee to specify
-how regrouped values should be combined. The iteratee
is bound to thisArg
-and invoked with four arguments: (accumulator, value, index, group).
array
(Array): The array of grouped elements to process.[iteratee]
(Function): The function to combine regrouped values.[thisArg]
(*): The this
binding of iteratee
.(Array): Returns the new array of regrouped elements.
-var zipped = _.zip([1, 2], [10, 20], [100, 200]);// => [[1, 10, 100], [2, 20, 200]] _.unzipWith(zipped, _.add);// => [3, 30, 300]
_.without(array, [values])
Creates an array excluding all provided values using
-SameValueZero
-for equality comparisons.
array
(Array): The array to filter.[values]
(...*): The values to exclude.(Array): Returns the new array of filtered values.
-_.without([1, 2, 1, 3], 1, 2);// => [3]
_.xor([arrays])
Creates an array of unique values that is the symmetric difference -of the provided arrays.
-[arrays]
(...Array): The arrays to inspect.(Array): Returns the new array of values.
-_.xor([1, 2], [4, 2]);// => [1, 4]
_.zip([arrays])
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.
-[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]]
_.zipObject(props, [values=[]])
The inverse of _.pairs
; this method returns an object composed from arrays
-of property names and values. Provide either a single two dimensional array,
-e.g. [[key1, value1], [key2, value2]]
or two arrays, one of property names
-and one of corresponding values.
_.object
-props
(Array): The property names.[values=[]]
(Array): The property values.(Object): Returns the new object.
-_.zipObject([['fred', 30], ['barney', 40]]);// => { 'fred': 30, 'barney': 40 } _.zipObject(['fred', 'barney'], [30, 40]);// => { 'fred': 30, 'barney': 40 }
_.zipWith([arrays], [iteratee], [thisArg])
This method is like _.zip
except that it accepts an iteratee to specify
-how grouped values should be combined. The iteratee
is bound to thisArg
-and invoked with four arguments: (accumulator, value, index, group).
[arrays]
(...Array): The arrays to process.[iteratee]
(Function): The function to combine grouped values.[thisArg]
(*): The this
binding of iteratee
.(Array): Returns the new array of grouped elements.
-_.zipWith([1, 2], [10, 20], [100, 200], _.add);// => [111, 222]
“Chain” Methods
_(value)
Creates a lodash
object which wraps value
to enable implicit chaining.
-Methods that operate on and return arrays, collections, and functions can
-be chained together. Methods that retrieve a single value or may return a
-primitive value will automatically end the chain returning the unwrapped
-value. Explicit chaining may be enabled using _.chain
. The execution of
-chained methods is lazy, that is, execution is deferred until _#value
-is implicitly or explicitly called.
-
-
-Lazy evaluation allows several methods to support shortcut fusion. Shortcut
-fusion is an optimization strategy which merge iteratee calls; this can help
-to avoid the creation of intermediate data structures and greatly reduce the
-number of iteratee executions.
-
-
-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
, reverse
, shift
, slice
, sort
,
-splice
, and unshift
-
-
-The wrapper String
methods are:
-replace
and split
-
-
-The wrapper methods that support shortcut fusion are:
-compact
, drop
, dropRight
, dropRightWhile
, dropWhile
, filter
,
-first
, initial
, last
, map
, pluck
, reject
, rest
, reverse
,
-slice
, take
, takeRight
, takeRightWhile
, takeWhile
, toArray
,
-and where
-
-
-The chainable wrapper methods are:
-after
, ary
, assign
, at
, before
, bind
, bindAll
, bindKey
,
-callback
, chain
, chunk
, commit
, compact
, concat
, constant
,
-countBy
, create
, curry
, debounce
, defaults
, defaultsDeep
,
-defer
, delay
, difference
, drop
, dropRight
, dropRightWhile
,
-dropWhile
, fill
, filter
, flatten
, flattenDeep
, flow
, flowRight
,
-forEach
, forEachRight
, forIn
, forInRight
, forOwn
, forOwnRight
,
-functions
, groupBy
, indexBy
, initial
, intersection
, invert
,
-invoke
, keys
, keysIn
, map
, mapKeys
, mapValues
, matches
,
-matchesProperty
, memoize
, merge
, method
, methodOf
, mixin
,
-modArgs
, negate
, omit
, once
, pairs
, partial
, partialRight
,
-partition
, pick
, plant
, pluck
, property
, propertyOf
, pull
,
-pullAt
, push
, range
, rearg
, reject
, remove
, rest
, restParam
,
-reverse
, set
, shuffle
, slice
, sort
, sortBy
, sortByAll
,
-sortByOrder
, splice
, spread
, take
, takeRight
, takeRightWhile
,
-takeWhile
, tap
, throttle
, thru
, times
, toArray
, toPlainObject
,
-transform
, union
, uniq
, unshift
, unzip
, unzipWith
, values
,
-valuesIn
, where
, without
, wrap
, xor
, zip
, zipObject
, zipWith
-
-
-The wrapper methods that are not chainable by default are:
-add
, attempt
, camelCase
, capitalize
, ceil
, clone
, cloneDeep
,
-deburr
, endsWith
, escape
, escapeRegExp
, every
, find
, findIndex
,
-findKey
, findLast
, findLastIndex
, findLastKey
, findWhere
, first
,
-floor
, get
, gt
, gte
, has
, identity
, includes
, indexOf
,
-inRange
, isArguments
, isArray
, isBoolean
, isDate
, isElement
,
-isEmpty
, isEqual
, isError
, isFinite
isFunction
, isMatch
,
-isNative
, isNaN
, isNull
, isNumber
, isObject
, isPlainObject
,
-isRegExp
, isString
, isUndefined
, isTypedArray
, join
, kebabCase
,
-last
, lastIndexOf
, lt
, lte
, max
, min
, noConflict
, noop
,
-now
, pad
, padLeft
, padRight
, parseInt
, pop
, random
, reduce
,
-reduceRight
, repeat
, result
, round
, runInContext
, shift
, size
,
-snakeCase
, some
, sortedIndex
, sortedLastIndex
, startCase
,
-startsWith
, sum
, template
, trim
, trimLeft
, trimRight
, trunc
,
-unescape
, uniqueId
, value
, and words
-
-
-The wrapper method sample
will return a wrapped value when n
is provided,
-otherwise an unwrapped value is returned.
value
(*): The value to wrap in a lodash
instance.(Object): Returns the new lodash
wrapper instance.
var wrapped = _([1, 2, 3]); // returns an unwrapped valuewrapped.reduce(function(total, n) { return total + n;});// => 6 // returns a wrapped valuevar squares = wrapped.map(function(n) { return n * n;}); _.isArray(squares);// => false _.isArray(squares.value());// => true
_.chain(value)
Creates a lodash
object that wraps value
with explicit method
-chaining enabled.
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(chr) { return chr.user + ' is ' + chr.age; }) .first() .value();// => 'pebbles is 1'
_.tap(value, interceptor, [thisArg])
This method invokes interceptor
and returns value
. The interceptor is
-bound to thisArg
and invoked with one argument; (value). The purpose of
-this method is to "tap into" a method chain in order to perform operations
-on intermediate results within the chain.
value
(*): The value to provide to interceptor
.interceptor
(Function): The function to invoke.[thisArg]
(*): The this
binding of interceptor
.(*): Returns value
.
_([1, 2, 3]) .tap(function(array) { array.pop(); }) .reverse() .value();// => [2, 1]
_.thru(value, interceptor, [thisArg])
This method is like _.tap
except that it returns the result of interceptor
.
value
(*): The value to provide to interceptor
.interceptor
(Function): The function to invoke.[thisArg]
(*): The this
binding of interceptor
.(*): Returns the result of interceptor
.
_(' abc ') .chain() .trim() .thru(function(value) { return [value]; }) .value();// => ['abc']
_.prototype.chain()
Enables explicit method chaining on the wrapper object.
-(Object): Returns the new lodash
wrapper instance.
var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }]; // without explicit chaining_(users).first();// => { 'user': 'barney', 'age': 36 } // with explicit chaining_(users).chain() .first() .pick('user') .value();// => { 'user': 'barney' }
_.prototype.commit()
Executes the chained sequence and returns the wrapped result.
-(Object): Returns the new lodash
wrapper instance.
var array = [1, 2];var wrapped = _(array).push(3); console.log(array);// => [1, 2] wrapped = wrapped.commit();console.log(array);// => [1, 2, 3] wrapped.last();// => 3 console.log(array);// => [1, 2, 3]
_.prototype.concat([values])
Creates a new array joining a wrapped array with any additional arrays -and/or values.
-[values]
(...*): The values to concatenate.(Array): Returns the new concatenated array.
-var array = [1];var wrapped = _(array).concat(2, [3], [[4]]); console.log(wrapped.value());// => [1, 2, 3, [4]] console.log(array);// => [1]
_.prototype.plant()
Creates a clone of the chained sequence planting value
as the wrapped value.
(Object): Returns the new lodash
wrapper instance.
var array = [1, 2];var wrapped = _(array).map(function(value) { return Math.pow(value, 2);}); var other = [3, 4];var otherWrapped = wrapped.plant(other); otherWrapped.value();// => [9, 16] wrapped.value();// => [1, 4]
_.prototype.reverse()
Reverses the wrapped array so the first element becomes the last, the
-second element becomes the second to last, and so on.
-
-
-Note: This method mutates the wrapped array.
(Object): Returns the new reversed lodash
wrapper instance.
var array = [1, 2, 3]; _(array).reverse().value()// => [3, 2, 1] console.log(array);// => [3, 2, 1]
_.prototype.toString()
Produces the result of coercing the unwrapped value to a string.
-(string): Returns the coerced string value.
-_([1, 2, 3]).toString();// => '1,2,3'
“Collection” Methods
_.at(collection, [props])
Creates an array of elements corresponding to the given keys, or indexes,
-of collection
. Keys may be specified as individual arguments or as arrays
-of keys.
collection
(Array|Object|string): The collection to iterate over.[props]
(...(number|number[]|string|string[])): The property names or indexes of elements to pick, specified individually or in arrays.(Array): Returns the new array of picked elements.
-_.at(['a', 'b', 'c'], [0, 2]);// => ['a', 'c'] _.at(['barney', 'fred', 'pebbles'], 0, 2);// => ['barney', 'pebbles']
_.countBy(collection, [iteratee=_.identity], [thisArg])
Creates an object composed of keys generated from the results of running
-each element of collection
through iteratee
. The corresponding value
-of each key is the number of times the key was returned by iteratee
.
-The iteratee
is bound to thisArg
and invoked with three arguments:
-(value, index|key, collection).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns the composed aggregate object.
-_.countBy([4.3, 6.1, 6.4], function(n) { return Math.floor(n);});// => { '4': 1, '6': 2 } _.countBy([4.3, 6.1, 6.4], function(n) { return this.floor(n);}, Math);// => { '4': 1, '6': 2 } _.countBy(['one', 'two', 'three'], 'length');// => { '3': 2, '5': 1 }
_.every(collection, [predicate=_.identity], [thisArg])
Checks if predicate
returns truthy for all elements of collection
.
-The predicate is bound to thisArg
and invoked with three arguments:
-(value, index|key, collection).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
_.all
-collection
(Array|Object|string): The collection to iterate over.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(boolean): Returns true
if all elements pass the predicate check, else false
.
_.every([true, 1, null, 'yes'], Boolean);// => false var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }]; // using the `_.matches` callback shorthand_.every(users, { 'user': 'barney', 'active': false });// => false // using the `_.matchesProperty` callback shorthand_.every(users, 'active', false);// => true // using the `_.property` callback shorthand_.every(users, 'active');// => false
_.filter(collection, [predicate=_.identity], [thisArg])
Iterates over elements of collection
, returning an array of all elements
-predicate
returns truthy for. The predicate is bound to thisArg
and
-invoked with three arguments: (value, index|key, collection).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
_.select
-collection
(Array|Object|string): The collection to iterate over.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the new filtered array.
-_.filter([4, 5, 6], function(n) { return n % 2 == 0;});// => [4, 6] var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }]; // using the `_.matches` callback shorthand_.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');// => ['barney'] // using the `_.matchesProperty` callback shorthand_.pluck(_.filter(users, 'active', false), 'user');// => ['fred'] // using the `_.property` callback shorthand_.pluck(_.filter(users, 'active'), 'user');// => ['barney']
_.find(collection, [predicate=_.identity], [thisArg])
Iterates over elements of collection
, returning the first element
-predicate
returns truthy for. The predicate is bound to thisArg
and
-invoked with three arguments: (value, index|key, collection).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
_.detect
-collection
(Array|Object|string): The collection to search.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(*): 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 }]; _.result(_.find(users, function(chr) { return chr.age < 40;}), 'user');// => 'barney' // using the `_.matches` callback shorthand_.result(_.find(users, { 'age': 1, 'active': true }), 'user');// => 'pebbles' // using the `_.matchesProperty` callback shorthand_.result(_.find(users, 'active', false), 'user');// => 'fred' // using the `_.property` callback shorthand_.result(_.find(users, 'active'), 'user');// => 'barney'
_.findLast(collection, [predicate=_.identity], [thisArg])
This method is like _.find
except that it iterates over elements of
-collection
from right to left.
collection
(Array|Object|string): The collection to search.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(*): Returns the matched element, else undefined
.
_.findLast([1, 2, 3, 4], function(n) { return n % 2 == 1;});// => 3
_.findWhere(collection, source)
Performs a deep comparison between each element in collection
and the
-source object, returning the first element that has equivalent property
-values.
-
-
-Note: This method supports comparing arrays, booleans, Date
objects,
-numbers, Object
objects, regexes, and strings. Objects are compared by
-their own, not inherited, enumerable properties. For comparing a single
-own or inherited property value see _.matchesProperty
.
collection
(Array|Object|string): The collection to search.source
(Object): The object of property values to match.(*): Returns the matched element, else undefined
.
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }]; _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');// => 'barney' _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');// => 'fred'
_.forEach(collection, [iteratee=_.identity], [thisArg])
Iterates over elements of collection
invoking iteratee
for each element.
-The iteratee
is bound to thisArg
and 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 _.forIn
or _.forOwn
-may be used for object iteration.
_.each
-collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(*): Returns collection
.
_([1, 2]).forEach(function(n) { console.log(n);}).value();// => logs each value from left to right and returns the array _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { console.log(n, key);});// => logs each value-key pair and returns the object (iteration order is not guaranteed)
_.forEachRight(collection, [iteratee=_.identity], [thisArg])
This method is like _.forEach
except that it iterates over elements of
-collection
from right to left.
_.eachRight
-collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(*): Returns collection
.
_([1, 2]).forEachRight(function(n) { console.log(n);}).value();// => logs each value from right to left and returns the array
_.groupBy(collection, [iteratee=_.identity], [thisArg])
Creates an object composed of keys generated from the results of running
-each element of collection
through iteratee
. The corresponding value
-of each key is an array of the elements responsible for generating the key.
-The iteratee
is bound to thisArg
and invoked with three arguments:
-(value, index|key, collection).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns the composed aggregate object.
-_.groupBy([4.2, 6.1, 6.4], function(n) { return Math.floor(n);});// => { '4': [4.2], '6': [6.1, 6.4] } _.groupBy([4.2, 6.1, 6.4], function(n) { return this.floor(n);}, Math);// => { '4': [4.2], '6': [6.1, 6.4] } // using the `_.property` callback shorthand_.groupBy(['one', 'two', 'three'], 'length');// => { '3': ['one', 'two'], '5': ['three'] }
_.includes(collection, target, [fromIndex=0])
Checks if target
is in collection
using
-SameValueZero
-for equality comparisons. If fromIndex
is negative, it's used as the offset
-from the end of collection
.
_.contains, _.include
-collection
(Array|Object|string): The collection to search.target
(*): The value to search for.[fromIndex=0]
(number): The index to search from.(boolean): Returns true
if a matching element is found, else false
.
_.includes([1, 2, 3], 1);// => true _.includes([1, 2, 3], 1, 2);// => false _.includes({ 'user': 'fred', 'age': 40 }, 'fred');// => true _.includes('pebbles', 'eb');// => true
_.indexBy(collection, [iteratee=_.identity], [thisArg])
Creates an object composed of keys generated from the results of running
-each element of collection
through iteratee
. The corresponding value
-of each key is the last element responsible for generating the key. The
-iteratee function is bound to thisArg
and invoked with three arguments:
-(value, index|key, collection).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns the composed aggregate object.
-var keyData = [ { 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 }]; _.indexBy(keyData, 'dir');// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } _.indexBy(keyData, function(object) { return String.fromCharCode(object.code);});// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } _.indexBy(keyData, function(object) { return this.fromCharCode(object.code);}, String);// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
_.invoke(collection, path, [args])
Invokes the method at path
of each element in collection
, returning
-an array of the results of each invoked method. Any additional arguments
-are provided to each invoked method. If methodName
is a function it's
-invoked for, and this
bound to, each element in collection
.
collection
(Array|Object|string): The collection to iterate over.path
(Array|Function|string): The path of the method to invoke or the function invoked per iteration.[args]
(...*): The arguments to invoke the method with.(Array): Returns the array of results.
-_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');// => [[1, 5, 7], [1, 2, 3]] _.invoke([123, 456], String.prototype.split, '');// => [['1', '2', '3'], ['4', '5', '6']]
_.map(collection, [iteratee=_.identity], [thisArg])
Creates an array of values by running each element in collection
through
-iteratee
. The iteratee
is bound to thisArg
and invoked with three
-arguments: (value, index|key, collection).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
-
-
-Many lodash methods are guarded to work as iteratees for methods like
-_.every
, _.filter
, _.map
, _.mapValues
, _.reject
, and _.some
.
-
-
-The guarded methods are:
-ary
, callback
, chunk
, clone
, create
, curry
, curryRight
,
-drop
, dropRight
, every
, fill
, flatten
, invert
, max
, min
,
-parseInt
, slice
, sortBy
, take
, takeRight
, template
, trim
,
-trimLeft
, trimRight
, trunc
, random
, range
, sample
, some
,
-sum
, uniq
, and words
_.collect
-collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Array): Returns the new mapped array.
-function timesThree(n) { return n * 3;} _.map([1, 2], timesThree);// => [3, 6] _.map({ 'a': 1, 'b': 2 }, timesThree);// => [3, 6] (iteration order is not guaranteed) var users = [ { 'user': 'barney' }, { 'user': 'fred' }]; // using the `_.property` callback shorthand_.map(users, 'user');// => ['barney', 'fred']
_.partition(collection, [predicate=_.identity], [thisArg])
Creates an array of elements split into two groups, the first of which
-contains elements predicate
returns truthy for, while the second of which
-contains elements predicate
returns falsey for. The predicate is bound
-to thisArg
and invoked with three arguments: (value, index|key, collection).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the array of grouped elements.
-_.partition([1, 2, 3], function(n) { return n % 2;});// => [[1, 3], [2]] _.partition([1.2, 2.3, 3.4], function(n) { return this.floor(n) % 2;}, Math);// => [[1.2, 3.4], [2.3]] var users = [ { 'user': 'barney', 'age': 36, 'active': false }, { 'user': 'fred', 'age': 40, 'active': true }, { 'user': 'pebbles', 'age': 1, 'active': false }]; var mapper = function(array) { return _.pluck(array, 'user');}; // using the `_.matches` callback shorthand_.map(_.partition(users, { 'age': 1, 'active': false }), mapper);// => [['pebbles'], ['barney', 'fred']] // using the `_.matchesProperty` callback shorthand_.map(_.partition(users, 'active', false), mapper);// => [['barney', 'pebbles'], ['fred']] // using the `_.property` callback shorthand_.map(_.partition(users, 'active'), mapper);// => [['fred'], ['barney', 'pebbles']]
_.pluck(collection, path)
Gets the property value of path
from all elements in collection
.
collection
(Array|Object|string): The collection to iterate over.path
(Array|string): The path of the property to pluck.(Array): Returns the property values.
-var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }]; _.pluck(users, 'user');// => ['barney', 'fred'] var userIndex = _.indexBy(users, 'user');_.pluck(userIndex, 'age');// => [36, 40] (iteration order is not guaranteed)
_.reduce(collection, [iteratee=_.identity], [accumulator], [thisArg])
Reduces collection
to a value which is the accumulated result of running
-each element in collection
through iteratee
, where each successive
-invocation is supplied the return value of the previous. If accumulator
-is not provided the first element of collection
is used as the initial
-value. The iteratee
is bound to thisArg
and 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
, sortByAll
,
-and sortByOrder
_.foldl, _.inject
-collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[accumulator]
(*): The initial value.[thisArg]
(*): The this
binding of iteratee
.(*): Returns the accumulated value.
-_.reduce([1, 2], function(total, n) { return total + n;});// => 3 _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { result[key] = n * 3; return result;}, {});// => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
_.reduceRight(collection, [iteratee=_.identity], [accumulator], [thisArg])
This method is like _.reduce
except that it iterates over elements of
-collection
from right to left.
_.foldr
-collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[accumulator]
(*): The initial value.[thisArg]
(*): The this
binding of iteratee
.(*): Returns the accumulated value.
-var array = [[0, 1], [2, 3], [4, 5]]; _.reduceRight(array, function(flattened, other) { return flattened.concat(other);}, []);// => [4, 5, 2, 3, 0, 1]
_.reject(collection, [predicate=_.identity], [thisArg])
The opposite of _.filter
; this method returns the elements of collection
-that predicate
does not return truthy for.
collection
(Array|Object|string): The collection to iterate over.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(Array): Returns the new filtered array.
-_.reject([1, 2, 3, 4], function(n) { return n % 2 == 0;});// => [1, 3] var users = [ { 'user': 'barney', 'age': 36, 'active': false }, { 'user': 'fred', 'age': 40, 'active': true }]; // using the `_.matches` callback shorthand_.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');// => ['barney'] // using the `_.matchesProperty` callback shorthand_.pluck(_.reject(users, 'active', false), 'user');// => ['fred'] // using the `_.property` callback shorthand_.pluck(_.reject(users, 'active'), 'user');// => ['barney']
_.sample(collection, [n])
Gets a random element or n
random elements from a collection.
collection
(Array|Object|string): The collection to sample.[n]
(number): The number of elements to sample.(*): Returns the random sample(s).
-_.sample([1, 2, 3, 4]);// => 2 _.sample([1, 2, 3, 4], 2);// => [3, 1]
_.shuffle(collection)
Creates an array of shuffled values, using a version of the -Fisher-Yates shuffle.
-collection
(Array|Object|string): The collection to shuffle.(Array): Returns the new shuffled array.
-_.shuffle([1, 2, 3, 4]);// => [4, 1, 3, 2]
_.size(collection)
Gets the size of collection
by returning its length for array-like
-values or the number of own enumerable properties for objects.
collection
(Array|Object|string): The collection to inspect.(number): Returns the size of collection
.
_.size([1, 2, 3]);// => 3 _.size({ 'a': 1, 'b': 2 });// => 2 _.size('pebbles');// => 7
_.some(collection, [predicate=_.identity], [thisArg])
Checks if predicate
returns truthy for any element of collection
.
-The function returns as soon as it finds a passing value and does not iterate
-over the entire collection. The predicate is bound to thisArg
and invoked
-with three arguments: (value, index|key, collection).
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
_.any
-collection
(Array|Object|string): The collection to iterate over.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(boolean): Returns true
if any element passes the predicate check, else false
.
_.some([null, 0, 'yes', false], Boolean);// => true var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }]; // using the `_.matches` callback shorthand_.some(users, { 'user': 'barney', 'active': false });// => false // using the `_.matchesProperty` callback shorthand_.some(users, 'active', false);// => true // using the `_.property` callback shorthand_.some(users, 'active');// => true
_.sortBy(collection, [iteratee=_.identity], [thisArg])
Creates an array of elements, sorted in ascending order by the results of
-running each element in a collection through iteratee
. This method performs
-a stable sort, that is, it preserves the original sort order of equal elements.
-The iteratee
is bound to thisArg
and invoked with three arguments:
-(value, index|key, collection).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Array): Returns the new sorted array.
-_.sortBy([1, 2, 3], function(n) { return Math.sin(n);});// => [3, 1, 2] _.sortBy([1, 2, 3], function(n) { return this.sin(n);}, Math);// => [3, 1, 2] var users = [ { 'user': 'fred' }, { 'user': 'pebbles' }, { 'user': 'barney' }]; // using the `_.property` callback shorthand_.pluck(_.sortBy(users, 'user'), 'user');// => ['barney', 'fred', 'pebbles']
_.sortByAll(collection, iteratees)
This method is like _.sortBy
except that it can sort by multiple iteratees
-or property names.
-
-
-If a property name is provided for an iteratee the created _.property
-style callback returns the property value of the given element.
-
-
-If an object is provided for an iteratee the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.iteratees
(...(Function|Function[]|Object|Object[]|string|string[])): The iteratees to sort by, specified as individual values or arrays of values.(Array): Returns the new sorted array.
-var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 42 }, { 'user': 'barney', 'age': 34 }]; _.map(_.sortByAll(users, ['user', 'age']), _.values);// => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] _.map(_.sortByAll(users, 'user', function(chr) { return Math.floor(chr.age / 10);}), _.values);// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
_.sortByOrder(collection, iteratees, [orders])
This method is like _.sortByAll
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, a value is sorted in
-ascending order if its corresponding order is "asc", and descending if "desc".
-
-
-If a property name is provided for an iteratee the created _.property
-style callback returns the property value of the given element.
-
-
-If an object is provided for an iteratee the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.iteratees
(Function[]|Object[]|string[]): The iteratees to sort by.[orders]
(boolean[]): The sort orders of iteratees
.(Array): Returns the new sorted array.
-var users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 34 }, { 'user': 'fred', 'age': 42 }, { 'user': 'barney', 'age': 36 }]; // sort by `user` in ascending order and by `age` in descending order_.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
_.where(collection, source)
Performs a deep comparison between each element in collection
and the
-source object, returning an array of all elements that have equivalent
-property values.
-
-
-Note: This method supports comparing arrays, booleans, Date
objects,
-numbers, Object
objects, regexes, and strings. Objects are compared by
-their own, not inherited, enumerable properties. For comparing a single
-own or inherited property value see _.matchesProperty
.
collection
(Array|Object|string): The collection to search.source
(Object): The object of property values to match.(Array): Returns the new filtered array.
-var users = [ { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }]; _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');// => ['barney'] _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');// => ['fred']
“Date” Methods
“Function” Methods
_.after(n, func)
The opposite of _.before
; this method creates a function that invokes
-func
once it's called n
or more times.
n
(number): The number of calls before func
is invoked.func
(Function): The function to restrict.(Function): Returns the new restricted function.
-var saves = ['profile', 'settings']; var done = _.after(saves.length, function() { console.log('done saving!');}); _.forEach(saves, function(type) { asyncSave({ 'type': type, 'complete': done });});// => logs 'done saving!' after the two async saves have completed
_.ary(func, [n=func.length])
Creates a function that accepts up to n
arguments ignoring any
-additional arguments.
func
(Function): The function to cap arguments for.[n=func.length]
(number): The arity cap.(Function): Returns the new function.
-_.map(['6', '8', '10'], _.ary(parseInt, 1));// => [6, 8, 10]
_.before(n, func)
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.
n
(number): The number of calls at which func
is no longer invoked.func
(Function): The function to restrict.(Function): Returns the new restricted function.
-jQuery('#add').on('click', _.before(5, addContactToList));// => allows adding up to 4 contacts to the list
_.bind(func, thisArg, [partials])
Creates a function that invokes func
with the this
binding of thisArg
-and prepends any additional _.bind
arguments to those provided to the
-bound function.
-
-
-The _.bind.placeholder
value, which defaults to _
in monolithic builds,
-may be used as a placeholder for partially applied arguments.
-
-
-Note: Unlike native Function#bind
this method does not set the "length"
-property of bound functions.
func
(Function): The function to bind.thisArg
(*): The this
binding of func
.[partials]
(...*): The arguments to be partially applied.(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!' // using placeholdersvar bound = _.bind(greet, object, _, '!');bound('hi');// => 'hi fred!'
_.bindAll(object, [methodNames])
Binds methods of an object to the object itself, overwriting the existing
-method. Method names may be specified as individual arguments or as arrays
-of method names. If no method names are provided all enumerable function
-properties, own and inherited, of object
are bound.
-
-
-Note: This method does not set the "length" property of bound functions.
object
(Object): The object to bind and assign the bound methods to.[methodNames]
(...(string|string[])): The object method names to bind, specified as individual method names or arrays of method names.(Object): Returns object
.
var view = { 'label': 'docs', 'onClick': function() { console.log('clicked ' + this.label); }}; _.bindAll(view);jQuery('#docs').on('click', view.onClick);// => logs 'clicked docs' when the element is clicked
_.bindKey(object, key, [partials])
Creates a function that invokes the method at object[key]
and prepends
-any additional _.bindKey
arguments to those provided to the bound function.
-
-
-This method differs from _.bind
by allowing bound functions to reference
-methods that may be redefined or don't yet exist.
-See Peter Michaux's article
-for more details.
-
-
-The _.bindKey.placeholder
value, which defaults to _
in monolithic
-builds, may be used as a placeholder for partially applied arguments.
object
(Object): The object the method belongs to.key
(string): The key of the method.[partials]
(...*): The arguments to be partially applied.(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!' // using placeholdersvar bound = _.bindKey(object, 'greet', _, '!');bound('hi');// => 'hiya fred!'
_.curry(func, [arity=func.length])
Creates a function that accepts one or more arguments of func
that when
-called either invokes func
returning its result, if all func
arguments
-have been provided, or returns a function that accepts one or more of the
-remaining func
arguments, and so on. The arity of func
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 does not set the "length" property of curried functions.
func
(Function): The function to curry.[arity=func.length]
(number): The arity of func
.(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] // using placeholderscurried(1)(_, 3)(2);// => [1, 2, 3]
_.curryRight(func, [arity=func.length])
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 does not set the "length" property of curried functions.
func
(Function): The function to curry.[arity=func.length]
(number): The arity of func
.(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] // using placeholderscurried(3)(1, _)(2);// => [1, 2, 3]
_.debounce(func, [wait=0], [options])
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 invocations. Provide an options object to indicate that func
-should be invoked on the leading and/or trailing edge of the wait
timeout.
-Subsequent calls to the debounced function 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 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
.
func
(Function): The function to debounce.[wait=0]
(number): The number of milliseconds to delay.[options]
(Object): The options object.[options.leading=false]
(boolean): Specify invoking on the leading edge of the timeout.[options.maxWait]
(number): The maximum time func
is allowed to be delayed before it's invoked.[options.trailing=true]
(boolean): Specify invoking on the trailing edge of the timeout.(Function): Returns the new debounced function.
-// avoid costly calculations while the window size is in fluxjQuery(window).on('resize', _.debounce(calculateLayout, 150)); // invoke `sendMail` when the click event is fired, debouncing subsequent callsjQuery('#postbox').on('click', _.debounce(sendMail, 300, { 'leading': true, 'trailing': false})); // ensure `batchLog` is invoked once after 1 second of debounced callsvar source = new EventSource('/stream');jQuery(source).on('message', _.debounce(batchLog, 250, { 'maxWait': 1000})); // cancel a debounced callvar todoChanges = _.debounce(batchLog, 1000);Object.observe(models.todo, todoChanges); Object.observe(models, function(changes) { if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { todoChanges.cancel(); }}, ['delete']); // ...at some point `models.todo` is changedmodels.todo.completed = true; // ...before 1 second has passed `models.todo` is deleted// which cancels the debounced `todoChanges` calldelete models.todo;
_.defer(func, [args])
Defers invoking the func
until the current call stack has cleared. Any
-additional arguments are provided to func
when it's invoked.
func
(Function): The function to defer.[args]
(...*): The arguments to invoke the function with.(number): Returns the timer id.
-_.defer(function(text) { console.log(text);}, 'deferred');// logs 'deferred' after one or more milliseconds
_.delay(func, wait, [args])
Invokes func
after wait
milliseconds. Any additional arguments are
-provided to func
when it's invoked.
func
(Function): The function to delay.wait
(number): The number of milliseconds to delay invocation.[args]
(...*): The arguments to invoke the function with.(number): Returns the timer id.
-_.delay(function(text) { console.log(text);}, 1000, 'later');// => logs 'later' after one second
_.flow([funcs])
Creates a function that returns the result of invoking the provided
-functions with the this
binding of the created function, where each
-successive invocation is supplied the return value of the previous.
[funcs]
(...Function): Functions to invoke.(Function): Returns the new function.
-function square(n) { return n * n;} var addSquare = _.flow(_.add, square);addSquare(1, 2);// => 9
_.flowRight([funcs])
This method is like _.flow
except that it creates a function that
-invokes the provided functions from right to left.
_.backflow, _.compose
-[funcs]
(...Function): Functions to invoke.(Function): Returns the new function.
-function square(n) { return n * n;} var addSquare = _.flowRight(square, _.add);addSquare(1, 2);// => 9
_.memoize(func, [resolver])
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 coerced to a string and used as the
-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 get
, has
, and set
.
func
(Function): The function to have its output memoized.[resolver]
(Function): The function to resolve the cache key.(Function): Returns the new memoizing function.
-var upperCase = _.memoize(function(string) { return string.toUpperCase();}); upperCase('fred');// => 'FRED' // modifying the result cacheupperCase.cache.set('fred', 'BARNEY');upperCase('fred');// => 'BARNEY' // replacing `_.memoize.Cache`var object = { 'user': 'fred' };var other = { 'user': 'barney' };var identity = _.memoize(_.identity); identity(object);// => { 'user': 'fred' }identity(other);// => { 'user': 'fred' } _.memoize.Cache = WeakMap;var identity = _.memoize(_.identity); identity(object);// => { 'user': 'fred' }identity(other);// => { 'user': 'barney' }
_.modArgs(func, [transforms])
Creates a function that runs each argument through a corresponding -transform function.
-func
(Function): The function to wrap.[transforms]
(...(Function|Function[])): The functions to transform
-arguments, specified as individual functions or arrays of functions.(Function): Returns the new function.
-function doubled(n) { return n * 2;} function square(n) { return n * n;} var modded = _.modArgs(function(x, y) { return [x, y];}, square, doubled); modded(1, 2);// => [1, 4] modded(5, 10);// => [25, 20]
_.negate(predicate)
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.
predicate
(Function): The predicate to negate.(Function): Returns the new function.
-function isEven(n) { return n % 2 == 0;} _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));// => [1, 3, 5]
_.once(func)
Creates a function that is restricted to invoking func
once. Repeat calls
-to the function return the value of the first call. The func
is invoked
-with the this
binding and arguments of the created function.
func
(Function): The function to restrict.(Function): Returns the new restricted function.
-var initialize = _.once(createApplication);initialize();initialize();// `initialize` invokes `createApplication` once
_.partial(func, [partials])
Creates a function that invokes func
with partial
arguments prepended
-to those provided to the new function. This method is like _.bind
except
-it does not alter the this
binding.
-
-
-The _.partial.placeholder
value, which defaults to _
in monolithic
-builds, may be used as a placeholder for partially applied arguments.
-
-
-Note: This method does not set the "length" property of partially
-applied functions.
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' // using placeholdersvar greetFred = _.partial(greet, _, 'fred');greetFred('hi');// => 'hi fred'
_.partialRight(func, [partials])
This method is like _.partial
except that partially applied arguments
-are appended to those provided to the new function.
-
-
-The _.partialRight.placeholder
value, which defaults to _
in monolithic
-builds, may be used as a placeholder for partially applied arguments.
-
-
-Note: This method does not set the "length" property of partially
-applied functions.
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' // using placeholdersvar sayHelloTo = _.partialRight(greet, 'hello', _);sayHelloTo('fred');// => 'hello fred'
_.rearg(func, indexes)
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.
func
(Function): The function to rearrange arguments for.indexes
(...(number|number[])): The arranged argument indexes, specified as individual indexes or arrays of indexes.(Function): Returns the new function.
-var rearged = _.rearg(function(a, b, c) { return [a, b, c];}, 2, 0, 1); rearged('b', 'c', 'a')// => ['a', 'b', 'c'] var map = _.rearg(_.map, [1, 0]);map(function(n) { return n * 3;}, [1, 2, 3]);// => [3, 6, 9]
_.restParam(func, [start=func.length-1])
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.
func
(Function): The function to apply a rest parameter to.[start=func.length-1]
(number): The start position of the rest parameter.(Function): Returns the new function.
-var say = _.restParam(function(what, names) { return what + ' ' + _.initial(names).join(', ') + (_.size(names) > 1 ? ', & ' : '') + _.last(names);}); say('hello', 'fred', 'barney', 'pebbles');// => 'hello fred, barney, & pebbles'
_.spread(func)
Creates a function that invokes func
with the this
binding of the created
-function and an array of arguments much like Function#apply
.
-
-
-Note: This method is based on the spread operator.
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' // with a Promisevar numbers = Promise.all([ Promise.resolve(40), Promise.resolve(36)]); numbers.then(_.spread(function(x, y) { return x + y;}));// => a Promise of 76
_.throttle(func, [wait=0], [options])
Creates a throttled function that only invokes func
at most once per
-every wait
milliseconds. The throttled function comes with a cancel
-method to cancel delayed invocations. Provide an options object to indicate
-that func
should be invoked on the leading and/or trailing edge of the
-wait
timeout. Subsequent calls to the throttled function return the
-result of the last func
call.
-
-
-Note: If leading
and trailing
options are true
, func
is invoked
-on the trailing edge of the timeout only if the 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
.
func
(Function): The function to throttle.[wait=0]
(number): The number of milliseconds to throttle invocations to.[options]
(Object): The options object.[options.leading=true]
(boolean): Specify invoking on the leading edge of the timeout.[options.trailing=true]
(boolean): Specify invoking on the trailing edge of the timeout.(Function): Returns the new throttled function.
-// avoid excessively updating the position while scrollingjQuery(window).on('scroll', _.throttle(updatePosition, 100)); // invoke `renewToken` when the click event is fired, but not more than once every 5 minutesjQuery('.interactive').on('click', _.throttle(renewToken, 300000, { 'trailing': false})); // cancel a trailing throttled calljQuery(window).on('popstate', throttled.cancel);
_.wrap(value, wrapper)
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.
value
(*): The value to wrap.wrapper
(Function): The wrapper function.(Function): Returns the new function.
-var p = _.wrap(_.escape, function(func, text) { return '<p>' + func(text) + '</p>';}); p('fred, barney, & pebbles');// => '<p>fred, barney, & pebbles</p>'
“Lang” Methods
_.clone(value, [isDeep], [customizer], [thisArg])
Creates a clone of value
. If isDeep
is true
nested objects are cloned,
-otherwise they are assigned by reference. If customizer
is provided it's
-invoked to produce the cloned values. If customizer
returns undefined
-cloning is handled by the method instead. The customizer
is bound to
-thisArg
and invoked with up to three argument; (value [, index|key, object]).
-
-
-Note: This method is loosely based on the
-structured clone algorithm.
-The enumerable properties of arguments
objects and objects created by
-constructors other than Object
are cloned to plain Object
objects. An
-empty object is returned for uncloneable values such as functions, DOM nodes,
-Maps, Sets, and WeakMaps.
value
(*): The value to clone.[isDeep]
(boolean): Specify a deep clone.[customizer]
(Function): The function to customize cloning values.[thisArg]
(*): The this
binding of customizer
.(*): Returns the cloned value.
-var users = [ { 'user': 'barney' }, { 'user': 'fred' }]; var shallow = _.clone(users);shallow[0] === users[0];// => true var deep = _.clone(users, true);deep[0] === users[0];// => false // using a customizer callbackvar el = _.clone(document.body, function(value) { if (_.isElement(value)) { return value.cloneNode(false); }}); el === document.body// => falseel.nodeName// => BODYel.childNodes.length;// => 0
_.cloneDeep(value, [customizer], [thisArg])
Creates a deep clone of value
. If customizer
is provided it's invoked
-to produce the cloned values. If customizer
returns undefined
cloning
-is handled by the method instead. The customizer
is bound to thisArg
-and invoked with up to three argument; (value [, index|key, object]).
-
-
-Note: This method is loosely based on the
-structured clone algorithm.
-The enumerable properties of arguments
objects and objects created by
-constructors other than Object
are cloned to plain Object
objects. An
-empty object is returned for uncloneable values such as functions, DOM nodes,
-Maps, Sets, and WeakMaps.
value
(*): The value to deep clone.[customizer]
(Function): The function to customize cloning values.[thisArg]
(*): The this
binding of customizer
.(*): Returns the deep cloned value.
-var users = [ { 'user': 'barney' }, { 'user': 'fred' }]; var deep = _.cloneDeep(users);deep[0] === users[0];// => false // using a customizer callbackvar el = _.cloneDeep(document.body, function(value) { if (_.isElement(value)) { return value.cloneNode(true); }}); el === document.body// => falseel.nodeName// => BODYel.childNodes.length;// => 20
_.gt(value, other)
Checks if value
is greater than other
.
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);// => false
_.gte(value, other)
Checks if value
is greater than or equal to other
.
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);// => false
_.isArguments(value)
Checks if value
is classified as an arguments
object.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isArguments(function() { return arguments; }());// => true _.isArguments([1, 2, 3]);// => false
_.isArray(value)
Checks if value
is classified as an Array
object.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isArray([1, 2, 3]);// => true _.isArray(function() { return arguments; }());// => false
_.isBoolean(value)
Checks if value
is classified as a boolean primitive or object.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isBoolean(false);// => true _.isBoolean(null);// => false
_.isDate(value)
Checks if value
is classified as a Date
object.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isDate(new Date);// => true _.isDate('Mon April 23 2012');// => false
_.isElement(value)
Checks if value
is a DOM element.
value
(*): The value to check.(boolean): Returns true
if value
is a DOM element, else false
.
_.isElement(document.body);// => true _.isElement('<body>');// => false
_.isEmpty(value)
Checks if value
is empty. A value is considered empty unless it's an
-arguments
object, array, string, or jQuery-like collection with a length
-greater than 0
or an object with own enumerable properties.
value
(Array|Object|string): The value to inspect.(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 });// => false
_.isEqual(value, other, [customizer], [thisArg])
Performs a deep comparison between two values to determine if they are
-equivalent. If customizer
is provided it's invoked to compare values.
-If customizer
returns undefined
comparisons are handled by the method
-instead. The customizer
is bound to thisArg
and invoked with up to
-three arguments: (value, other [, index|key]).
-
-
-Note: This method supports comparing arrays, booleans, Date
objects,
-numbers, Object
objects, regexes, and strings. Objects are compared by
-their own, not inherited, enumerable properties. Functions and DOM nodes
-are not supported. Provide a customizer function to extend support
-for comparing other values.
_.eq
-value
(*): The value to compare.other
(*): The other value to compare.[customizer]
(Function): The function to customize value comparisons.[thisArg]
(*): The this
binding of customizer
.(boolean): Returns true
if the values are equivalent, else false
.
var object = { 'user': 'fred' };var other = { 'user': 'fred' }; object == other;// => false _.isEqual(object, other);// => true // using a customizer callbackvar array = ['hello', 'goodbye'];var other = ['hi', 'goodbye']; _.isEqual(array, other, function(value, other) { if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { return true; }});// => true
_.isError(value)
Checks if value
is an Error
, EvalError
, RangeError
, ReferenceError
,
-SyntaxError
, TypeError
, or URIError
object.
value
(*): The value to check.(boolean): Returns true
if value
is an error object, else false
.
_.isError(new Error);// => true _.isError(Error);// => false
_.isFinite(value)
Checks if value
is a finite primitive number.
-
-
-Note: This method is based on Number.isFinite
.
value
(*): The value to check.(boolean): Returns true
if value
is a finite number, else false
.
_.isFinite(10);// => true _.isFinite('10');// => false _.isFinite(true);// => false _.isFinite(Object(10));// => false _.isFinite(Infinity);// => false
_.isFunction(value)
Checks if value
is classified as a Function
object.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isFunction(_);// => true _.isFunction(/abc/);// => false
_.isMatch(object, source, [customizer], [thisArg])
Performs a deep comparison between object
and source
to determine if
-object
contains equivalent property values. If customizer
is provided
-it's invoked to compare values. If customizer
returns undefined
-comparisons are handled by the method instead. The customizer
is bound
-to thisArg
and invoked with three arguments: (value, other, index|key).
-
-
-Note: This method supports comparing properties of arrays, booleans,
-Date
objects, numbers, Object
objects, regexes, and strings. Functions
-and DOM nodes are not supported. Provide a customizer function to extend
-support for comparing other values.
object
(Object): The object to inspect.source
(Object): The object of property values to match.[customizer]
(Function): The function to customize value comparisons.[thisArg]
(*): The this
binding of customizer
.(boolean): Returns true
if object
is a match, else false
.
var object = { 'user': 'fred', 'age': 40 }; _.isMatch(object, { 'age': 40 });// => true _.isMatch(object, { 'age': 36 });// => false // using a customizer callbackvar object = { 'greeting': 'hello' };var source = { 'greeting': 'hi' }; _.isMatch(object, source, function(value, other) { return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;});// => true
_.isNaN(value)
Checks if value
is NaN
.
-
-
-Note: This method is not the same as isNaN
-which returns true
for undefined
and other non-numeric values.
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);// => false
_.isNative(value)
Checks if value
is a native function.
value
(*): The value to check.(boolean): Returns true
if value
is a native function, else false
.
_.isNative(Array.prototype.push);// => true _.isNative(_);// => false
_.isNull(value)
Checks if value
is null
.
value
(*): The value to check.(boolean): Returns true
if value
is null
, else false
.
_.isNull(null);// => true _.isNull(void 0);// => false
_.isNumber(value)
Checks if value
is classified as a Number
primitive or object.
-
-
-Note: To exclude Infinity
, -Infinity
, and NaN
, which are classified
-as numbers, use the _.isFinite
method.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isNumber(8.4);// => true _.isNumber(NaN);// => true _.isNumber('8.4');// => false
_.isObject(value)
Checks if value
is the language type of Object
.
-(e.g. arrays, functions, objects, regexes, new Number(0)
, and new String('')
)
value
(*): The value to check.(boolean): Returns true
if value
is an object, else false
.
_.isObject({});// => true _.isObject([1, 2, 3]);// => true _.isObject(1);// => false
_.isPlainObject(value)
Checks if value
is a plain object, that is, an object created by the
-Object
constructor or one with a [[Prototype]]
of null
.
-
-
-Note: This method assumes objects created by the Object
constructor
-have no inherited enumerable properties.
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));// => true
_.isRegExp(value)
Checks if value
is classified as a RegExp
object.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isRegExp(/abc/);// => true _.isRegExp('/abc/');// => false
_.isString(value)
Checks if value
is classified as a String
primitive or object.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isString('abc');// => true _.isString(1);// => false
_.isTypedArray(value)
Checks if value
is classified as a typed array.
value
(*): The value to check.(boolean): Returns true
if value
is correctly classified, else false
.
_.isTypedArray(new Uint8Array);// => true _.isTypedArray([]);// => false
_.isUndefined(value)
Checks if value
is undefined
.
value
(*): The value to check.(boolean): Returns true
if value
is undefined
, else false
.
_.isUndefined(void 0);// => true _.isUndefined(null);// => false
_.lt(value, other)
Checks if value
is less than other
.
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);// => false
_.lte(value, other)
Checks if value
is less than or equal to other
.
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);// => false
_.toArray(value)
Converts value
to an array.
value
(*): The value to convert.(Array): Returns the converted array.
-(function() { return _.toArray(arguments).slice(1);}(1, 2, 3));// => [2, 3]
_.toPlainObject(value)
Converts value
to a plain object flattening inherited enumerable
-properties of value
to own properties of the plain object.
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 }
“Math” Methods
_.add(augend, addend)
Adds two numbers.
-augend
(number): The first number to add.addend
(number): The second number to add.(number): Returns the sum.
-_.add(6, 4);// => 10
_.ceil(n, [precision=0])
Calculates n
rounded up to precision
.
n
(number): The number to round up.[precision=0]
(number): The precision to round up to.(number): Returns the rounded up number.
-_.ceil(4.006);// => 5 _.ceil(6.004, 2);// => 6.01 _.ceil(6040, -2);// => 6100
_.floor(n, [precision=0])
Calculates n
rounded down to precision
.
n
(number): The number to round down.[precision=0]
(number): The precision to round down to.(number): Returns the rounded down number.
-_.floor(4.006);// => 4 _.floor(0.046, 2);// => 0.04 _.floor(4060, -2);// => 4000
_.max(collection, [iteratee], [thisArg])
Gets the maximum value of collection
. If collection
is empty or falsey
--Infinity
is returned. If an iteratee function is provided it's invoked
-for each value in collection
to generate the criterion by which the value
-is ranked. The iteratee
is bound to thisArg
and invoked with three
-arguments: (value, index, collection).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.[iteratee]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(*): Returns the maximum value.
-_.max([4, 2, 8, 6]);// => 8 _.max([]);// => -Infinity var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }]; _.max(users, function(chr) { return chr.age;});// => { 'user': 'fred', 'age': 40 } // using the `_.property` callback shorthand_.max(users, 'age');// => { 'user': 'fred', 'age': 40 }
_.min(collection, [iteratee], [thisArg])
Gets the minimum value of collection
. If collection
is empty or falsey
-Infinity
is returned. If an iteratee function is provided it's invoked
-for each value in collection
to generate the criterion by which the value
-is ranked. The iteratee
is bound to thisArg
and invoked with three
-arguments: (value, index, collection).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
collection
(Array|Object|string): The collection to iterate over.[iteratee]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(*): Returns the minimum value.
-_.min([4, 2, 8, 6]);// => 2 _.min([]);// => Infinity var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }]; _.min(users, function(chr) { return chr.age;});// => { 'user': 'barney', 'age': 36 } // using the `_.property` callback shorthand_.min(users, 'age');// => { 'user': 'barney', 'age': 36 }
_.round(n, [precision=0])
Calculates n
rounded to precision
.
n
(number): The number to round.[precision=0]
(number): The precision to round to.(number): Returns the rounded number.
-_.round(4.006);// => 4 _.round(4.006, 2);// => 4.01 _.round(4060, -2);// => 4100
_.sum(collection, [iteratee], [thisArg])
Gets the sum of the values in collection
.
collection
(Array|Object|string): The collection to iterate over.[iteratee]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(number): Returns the sum.
-_.sum([4, 6]);// => 10 _.sum({ 'a': 4, 'b': 6 });// => 10 var objects = [ { 'n': 4 }, { 'n': 6 }]; _.sum(objects, function(object) { return object.n;});// => 10 // using the `_.property` callback shorthand_.sum(objects, 'n');// => 10
“Number” Methods
_.inRange(n, [start=0], end)
Checks if n
is between start
and up to but not including, end
. If
-end
is not specified it's set to start
with start
then set to 0
.
n
(number): The number to check.[start=0]
(number): The start of the range.end
(number): The end of the range.(boolean): Returns true
if n
is in the range, else false
.
_.inRange(3, 2, 4);// => true _.inRange(4, 8);// => true _.inRange(4, 2);// => false _.inRange(2, 2);// => false _.inRange(1.2, 2);// => true _.inRange(5.2, 4);// => false
_.random([min=0], [max=1], [floating])
Produces a random number between min
and max
(inclusive). If only one
-argument is provided a number between 0
and the given number is returned.
-If floating
is true
, or either min
or max
are floats, a floating-point
-number is returned instead of an integer.
[min=0]
(number): The minimum possible value.[max=1]
(number): The maximum possible value.[floating]
(boolean): Specify returning a floating-point number.(number): Returns the random number.
-_.random(0, 5);// => an integer between 0 and 5 _.random(5);// => also an integer between 0 and 5 _.random(5, true);// => a floating-point number between 0 and 5 _.random(1.2, 5.2);// => a floating-point number between 1.2 and 5.2
“Object” Methods
_.assign(object, [sources], [customizer], [thisArg])
Assigns own enumerable properties of source object(s) to the destination
-object. Subsequent sources overwrite property assignments of previous sources.
-If customizer
is provided it's invoked to produce the assigned values.
-The customizer
is bound to thisArg
and invoked with five arguments:
-(objectValue, sourceValue, key, object, source).
-
-
-Note: This method mutates object
and is based on
-Object.assign
.
_.extend
-object
(Object): The destination object.[sources]
(...Object): The source objects.[customizer]
(Function): The function to customize assigned values.[thisArg]
(*): The this
binding of customizer
.(Object): Returns object
.
_.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });// => { 'user': 'fred', 'age': 40 } // using a customizer callbackvar defaults = _.partialRight(_.assign, function(value, other) { return _.isUndefined(value) ? other : value;}); defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });// => { 'user': 'barney', 'age': 36 }
_.create(prototype, [properties])
Creates an object that inherits from the given prototype
object. If a
-properties
object is provided its own enumerable properties are assigned
-to the created object.
prototype
(Object): The object to inherit from.[properties]
(Object): The properties to assign to the object.(Object): Returns the new object.
-function Shape() { this.x = 0; this.y = 0;} function Circle() { Shape.call(this);} Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle}); var circle = new Circle;circle instanceof Circle;// => true circle instanceof Shape;// => true
_.defaults(object, [sources])
Assigns own enumerable properties of source object(s) to the destination
-object for all destination properties that resolve to undefined
. Once a
-property is set, additional values of the same property are ignored.
-
-
-Note: This method mutates object
.
object
(Object): The destination object.[sources]
(...Object): The source objects.(Object): Returns object
.
_.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });// => { 'user': 'barney', 'age': 36 }
_.defaultsDeep(object, [sources])
This method is like _.defaults
except that it recursively assigns
-default properties.
-
-
-Note: This method mutates object
.
object
(Object): The destination object.[sources]
(...Object): The source objects.(Object): Returns object
.
_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });// => { 'user': { 'name': 'barney', 'age': 36 } }
_.findKey(object, [predicate=_.identity], [thisArg])
This method is like _.find
except that it returns the key of the first
-element predicate
returns truthy for instead of the element itself.
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
object
(Object): The object to search.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(*): 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(users, function(chr) { return chr.age < 40;});// => 'barney' (iteration order is not guaranteed) // using the `_.matches` callback shorthand_.findKey(users, { 'age': 1, 'active': true });// => 'pebbles' // using the `_.matchesProperty` callback shorthand_.findKey(users, 'active', false);// => 'fred' // using the `_.property` callback shorthand_.findKey(users, 'active');// => 'barney'
_.findLastKey(object, [predicate=_.identity], [thisArg])
This method is like _.findKey
except that it iterates over elements of
-a collection in the opposite order.
-
-
-If a property name is provided for predicate
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for predicate
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
object
(Object): The object to search.[predicate=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of predicate
.(*): 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(users, function(chr) { return chr.age < 40;});// => returns `pebbles` assuming `_.findKey` returns `barney` // using the `_.matches` callback shorthand_.findLastKey(users, { 'age': 36, 'active': true });// => 'barney' // using the `_.matchesProperty` callback shorthand_.findLastKey(users, 'active', false);// => 'fred' // using the `_.property` callback shorthand_.findLastKey(users, 'active');// => 'pebbles'
_.forIn(object, [iteratee=_.identity], [thisArg])
Iterates over own and inherited enumerable properties of an object invoking
-iteratee
for each property. The iteratee
is bound to thisArg
and invoked
-with three arguments: (value, key, object). Iteratee functions may exit
-iteration early by explicitly returning false
.
object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forIn(new Foo, function(value, key) { console.log(key);});// => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
_.forInRight(object, [iteratee=_.identity], [thisArg])
This method is like _.forIn
except that it iterates over properties of
-object
in the opposite order.
object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forInRight(new Foo, function(value, key) { console.log(key);});// => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
_.forOwn(object, [iteratee=_.identity], [thisArg])
Iterates over own enumerable properties of an object invoking iteratee
-for each property. The iteratee
is bound to thisArg
and invoked with
-three arguments: (value, key, object). Iteratee functions may exit iteration
-early by explicitly returning false
.
object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forOwn(new Foo, function(value, key) { console.log(key);});// => logs 'a' and 'b' (iteration order is not guaranteed)
_.forOwnRight(object, [iteratee=_.identity], [thisArg])
This method is like _.forOwn
except that it iterates over properties of
-object
in the opposite order.
object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forOwnRight(new Foo, function(value, key) { console.log(key);});// => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
_.functions(object)
Creates an array of function property names from all enumerable properties,
-own and inherited, of object
.
_.methods
-object
(Object): The object to inspect.(Array): Returns the new array of property names.
-_.functions(_);// => ['after', 'ary', 'assign', ...]
_.get(object, path, [defaultValue])
Gets the property value at path
of object
. If the resolved value is
-undefined
the defaultValue
is used in its place.
object
(Object): The object to query.path
(Array|string): The path of the property to get.[defaultValue]
(*): The value returned if the resolved value is undefined
.(*): Returns the resolved value.
-var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.get(object, 'a[0].b.c');// => 3 _.get(object, ['a', '0', 'b', 'c']);// => 3 _.get(object, 'a.b.c', 'default');// => 'default'
_.has(object, path)
Checks if path
is a direct property.
object
(Object): The object to query.path
(Array|string): The path to check.(boolean): Returns true
if path
is a direct property, else false
.
var object = { 'a': { 'b': { 'c': 3 } } }; _.has(object, 'a');// => true _.has(object, 'a.b.c');// => true _.has(object, ['a', 'b', 'c']);// => true
_.invert(object, [multiValue])
Creates an object composed of the inverted keys and values of object
.
-If object
contains duplicate values, subsequent values overwrite property
-assignments of previous values unless multiValue
is true
.
object
(Object): The object to invert.[multiValue]
(boolean): Allow multiple values per key.(Object): Returns the new inverted object.
-var object = { 'a': 1, 'b': 2, 'c': 1 }; _.invert(object);// => { '1': 'c', '2': 'b' } // with `multiValue`_.invert(object, true);// => { '1': ['a', 'c'], '2': ['b'] }
_.keys(object)
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.
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']
_.keysIn(object)
Creates an array of the own and inherited enumerable property names of object
.
-
-
-Note: Non-object values are coerced to objects.
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)
_.mapKeys(object, [iteratee=_.identity], [thisArg])
The opposite of _.mapValues
; this method creates an object with the
-same values as object
and keys generated by running each own enumerable
-property of object
through iteratee
.
object
(Object): The object to iterate over.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns the new mapped object.
-_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { return key + value;});// => { 'a1': 1, 'b2': 2 }
_.mapValues(object, [iteratee=_.identity], [thisArg])
Creates an object with the same keys as object
and values generated by
-running each own enumerable property of object
through iteratee
. The
-iteratee function is bound to thisArg
and invoked with three arguments:
-(value, key, object).
-
-
-If a property name is provided for iteratee
the created _.property
-style callback returns the property value of the given element.
-
-
-If a value is also provided for thisArg
the created _.matchesProperty
-style callback returns true
for elements that have a matching property
-value, else false
.
-
-
-If an object is provided for iteratee
the created _.matches
style
-callback returns true
for elements that have the properties of the given
-object, else false
.
object
(Object): The object to iterate over.[iteratee=_.identity]
(Function|Object|string): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Object): Returns the new mapped object.
-_.mapValues({ 'a': 1, 'b': 2 }, function(n) { return n * 3;});// => { 'a': 3, 'b': 6 } var users = { 'fred': { 'user': 'fred', 'age': 40 }, 'pebbles': { 'user': 'pebbles', 'age': 1 }}; // using the `_.property` callback shorthand_.mapValues(users, 'age');// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
_.merge(object, [sources], [customizer], [thisArg])
Recursively merges own enumerable properties of the source object(s), that
-don't resolve to undefined
into the destination object. Subsequent sources
-overwrite property assignments of previous sources. If customizer
is
-provided it's 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 bound to thisArg
and invoked
-with five arguments: (objectValue, sourceValue, key, object, source).
object
(Object): The destination object.[sources]
(...Object): The source objects.[customizer]
(Function): The function to customize assigned values.[thisArg]
(*): The this
binding of customizer
.(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 }] } // using a customizer callbackvar object = { 'fruits': ['apple'], 'vegetables': ['beet']}; var other = { 'fruits': ['banana'], 'vegetables': ['carrot']}; _.merge(object, other, function(a, b) { if (_.isArray(a)) { return a.concat(b); }});// => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
_.omit(object, [predicate], [thisArg])
The opposite of _.pick
; this method creates an object composed of the
-own and inherited enumerable properties of object
that are not omitted.
object
(Object): The source object.[predicate]
(...((string|string[])|Function)): The function invoked per iteration or property names to omit, specified as individual property names or arrays of property names.[thisArg]
(*): The this
binding of predicate
.(Object): Returns the new object.
-var object = { 'user': 'fred', 'age': 40 }; _.omit(object, 'age');// => { 'user': 'fred' } _.omit(object, _.isNumber);// => { 'user': 'fred' }
_.pairs(object)
Creates a two dimensional array of the key-value pairs for object
,
-e.g. [[key1, value1], [key2, value2]]
.
object
(Object): The object to query.(Array): Returns the new array of key-value pairs.
-_.pairs({ 'barney': 36, 'fred': 40 });// => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
_.pick(object, [predicate], [thisArg])
Creates an object composed of the picked object
properties. Property
-names may be specified as individual arguments or as arrays of property
-names. If predicate
is provided it's invoked for each property of object
-picking the properties predicate
returns truthy for. The predicate is
-bound to thisArg
and invoked with three arguments: (value, key, object).
object
(Object): The source object.[predicate]
(...((string|string[])|Function)): The function invoked per iteration or property names to pick, specified as individual property names or arrays of property names.[thisArg]
(*): The this
binding of predicate
.(Object): Returns the new object.
-var object = { 'user': 'fred', 'age': 40 }; _.pick(object, 'user');// => { 'user': 'fred' } _.pick(object, _.isString);// => { 'user': 'fred' }
_.result(object, path, [defaultValue])
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.
object
(Object): The object to query.path
(Array|string): The path of the property to resolve.[defaultValue]
(*): The value returned if the resolved value is undefined
.(*): Returns the resolved value.
-var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; _.result(object, 'a[0].b.c1');// => 3 _.result(object, 'a[0].b.c2');// => 4 _.result(object, 'a.b.c', 'default');// => 'default' _.result(object, 'a.b.c', _.constant('default'));// => 'default'
_.set(object, path, value)
Sets the property value of path
on object
. If a portion of path
-does not exist it's created.
object
(Object): The object to augment.path
(Array|string): The path of the property to set.value
(*): The value to set.(Object): Returns object
.
var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.set(object, 'a[0].b.c', 4);console.log(object.a[0].b.c);// => 4 _.set(object, 'x[0].y.z', 5);console.log(object.x[0].y.z);// => 5
_.transform(object, [iteratee=_.identity], [accumulator], [thisArg])
An alternative to _.reduce
; this method transforms object
to a new
-accumulator
object which is the result of running each of its own enumerable
-properties through iteratee
, with each invocation potentially mutating
-the accumulator
object. The iteratee
is bound to thisArg
and invoked
-with four arguments: (accumulator, value, key, object). Iteratee functions
-may exit iteration early by explicitly returning false
.
object
(Array|Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[accumulator]
(*): The custom accumulator value.[thisArg]
(*): The this
binding of iteratee
.(*): Returns the accumulated value.
-_.transform([2, 3, 4], function(result, n) { result.push(n *= n); return n % 2 == 0;});// => [4, 9] _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) { result[key] = n * 3;});// => { 'a': 3, 'b': 6 }
_.values(object)
Creates an array of the own enumerable property values of object
.
-
-
-Note: Non-object values are coerced to objects.
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']
_.valuesIn(object)
Creates an array of the own and inherited enumerable property values
-of object
.
-
-
-Note: Non-object values are coerced to objects.
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)
“String” Methods
_.camelCase([string=''])
Converts string
to camel case.
[string='']
(string): The string to convert.(string): Returns the camel cased string.
-_.camelCase('Foo Bar');// => 'fooBar' _.camelCase('--foo-bar');// => 'fooBar' _.camelCase('__foo_bar__');// => 'fooBar'
_.capitalize([string=''])
Capitalizes the first character of string
.
[string='']
(string): The string to capitalize.(string): Returns the capitalized string.
-_.capitalize('fred');// => 'Fred'
_.deburr([string=''])
Deburrs string
by converting latin-1 supplementary letters
-to basic latin letters and removing combining diacritical marks.
[string='']
(string): The string to deburr.(string): Returns the deburred string.
-_.deburr('déjà vu');// => 'deja vu'
_.endsWith([string=''], [target], [position=string.length])
Checks if string
ends with the given target string.
[string='']
(string): The string to search.[target]
(string): The string to search for.[position=string.length]
(number): The position to search from.(boolean): Returns true
if string
ends with target
, else false
.
_.endsWith('abc', 'c');// => true _.endsWith('abc', 'b');// => false _.endsWith('abc', 'b', 2);// => true
_.escape([string=''])
Converts the characters "&", "<", ">", '"', "'", and "`", in string
to
-their corresponding HTML entities.
-
-
-Note: No other characters are escaped. To escape additional characters
-use a third-party library like he.
-
-
-Though the ">" character is escaped for symmetry, characters like
-">" and "/" don't need escaping in HTML and have no special meaning
-unless they're part of a tag or unquoted attribute value.
-See Mathias Bynens's article
-(under "semi-related fun fact") for more details.
-
-
-Backticks are escaped because in Internet Explorer < 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.
[string='']
(string): The string to escape.(string): Returns the escaped string.
-_.escape('fred, barney, & pebbles');// => 'fred, barney, & pebbles'
_.escapeRegExp([string=''])
Escapes the RegExp
special characters "\", "/", "^", "$", ".", "|", "?",
-"*", "+", "(", ")", "[", "]", "{" and "}" in string
.
[string='']
(string): The string to escape.(string): Returns the escaped string.
-_.escapeRegExp('[lodash](https://lodash.com/)');// => '\[lodash\]\(https:\/\/lodash\.com\/\)'
_.kebabCase([string=''])
Converts string
to kebab case.
[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'
_.pad([string=''], [length=0], [chars=' '])
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
.
[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
-_.pad('abc', 8);// => ' abc ' _.pad('abc', 8, '_-');// => '_-abc_-_' _.pad('abc', 3);// => 'abc'
_.padLeft([string=''], [length=0], [chars=' '])
Pads string
on the left side if it's shorter than length
. Padding
-characters are truncated if they exceed length
.
[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
-_.padLeft('abc', 6);// => ' abc' _.padLeft('abc', 6, '_-');// => '_-_abc' _.padLeft('abc', 3);// => 'abc'
_.padRight([string=''], [length=0], [chars=' '])
Pads string
on the right side if it's shorter than length
. Padding
-characters are truncated if they exceed length
.
[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
-_.padRight('abc', 6);// => 'abc ' _.padRight('abc', 6, '_-');// => 'abc_-_' _.padRight('abc', 3);// => 'abc'
_.parseInt(string, [radix])
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
.
string
(string): The string to convert.[radix]
(number): The radix to interpret value
by.(number): Returns the converted integer.
-_.parseInt('08');// => 8 _.map(['6', '08', '10'], _.parseInt);// => [6, 8, 10]
_.repeat([string=''], [n=0])
Repeats the given string n
times.
[string='']
(string): The string to repeat.[n=0]
(number): The number of times to repeat the string.(string): Returns the repeated string.
-_.repeat('*', 3);// => '***' _.repeat('abc', 2);// => 'abcabc' _.repeat('abc', 0);// => ''
_.snakeCase([string=''])
Converts string
to snake case.
[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'
_.startCase([string=''])
Converts string
to start case.
[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'
_.startsWith([string=''], [target], [position=0])
Checks if string
starts with the given target string.
[string='']
(string): The string to search.[target]
(string): The string to search for.[position=0]
(number): The position to search from.(boolean): Returns true
if string
starts with target
, else false
.
_.startsWith('abc', 'a');// => true _.startsWith('abc', 'b');// => false _.startsWith('abc', 'b', 1);// => true
_.template([string=''], [options])
Creates a compiled template function that can interpolate data properties
-in "interpolate" delimiters, HTML-escape interpolated data properties in
-"escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
-properties may be accessed as free variables in the template. If a setting
-object is provided 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.
[string='']
(string): The template string.[options]
(Object): The options object.[options.escape]
(RegExp): The HTML "escape" delimiter.[options.evaluate]
(RegExp): The "evaluate" delimiter.[options.imports]
(Object): An object to import into the template as free variables.[options.interpolate]
(RegExp): The "interpolate" delimiter.[options.sourceURL]
(string): The sourceURL of the template's compiled source.[options.variable]
(string): The data object variable name.(Function): Returns the compiled template function.
-// using the "interpolate" delimiter to create a compiled templatevar compiled = _.template('hello <%= user %>!');compiled({ 'user': 'fred' });// => 'hello fred!' // using the HTML "escape" delimiter to escape data property valuesvar compiled = _.template('<b><%- value %></b>');compiled({ 'value': '<script>' });// => '<b><script></b>' // using the "evaluate" delimiter to execute JavaScript and generate HTMLvar compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');compiled({ 'users': ['fred', 'barney'] });// => '<li>fred</li><li>barney</li>' // using the internal `print` function in "evaluate" delimitersvar compiled = _.template('<% print("hello " + user); %>!');compiled({ 'user': 'barney' });// => 'hello barney!' // using the ES delimiter as an alternative to the default "interpolate" delimitervar compiled = _.template('hello ${ user }!');compiled({ 'user': 'pebbles' });// => 'hello pebbles!' // using custom template delimiters_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;var compiled = _.template('hello {{ user }}!');compiled({ 'user': 'mustache' });// => 'hello mustache!' // using backslashes to treat delimiters as plain textvar compiled = _.template('<%= "\\<%- value %\\>" %>');compiled({ 'value': 'ignored' });// => '<%- value %>' // using 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>' // using the `sourceURL` option to specify a custom sourceURL for the templatevar 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 // using the `variable` option to ensure a with-statement isn't used in the compiled templatevar compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });compiled.source;// => function(data) {// var __t, __p = '';// __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';// return __p;// } // using the `source` property to inline compiled templates for meaningful// line numbers in error messages and a stack tracefs.writeFileSync(path.join(cwd, 'jst.js'), '\ var JST = {\ "main": ' + _.template(mainText).source + '\ };\');
_.trim([string=''], [chars=whitespace])
Removes leading and trailing whitespace or specified characters from string
.
[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
-_.trim(' abc ');// => 'abc' _.trim('-_-abc-_-', '_-');// => 'abc' _.map([' foo ', ' bar '], _.trim);// => ['foo', 'bar']
_.trimLeft([string=''], [chars=whitespace])
Removes leading whitespace or specified characters from string
.
[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
-_.trimLeft(' abc ');// => 'abc ' _.trimLeft('-_-abc-_-', '_-');// => 'abc-_-'
_.trimRight([string=''], [chars=whitespace])
Removes trailing whitespace or specified characters from string
.
[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
-_.trimRight(' abc ');// => ' abc' _.trimRight('-_-abc-_-', '_-');// => '-_-abc'
_.trunc([string=''], [options], [options.length=30], [options.omission='...'], [options.separator])
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 "...".
[string='']
(string): The string to truncate.[options]
(Object|number): The options object or maximum string length.[options.length=30]
(number): The maximum string length.[options.omission='...']
(string): The string to indicate text is omitted.[options.separator]
(RegExp|string): The separator pattern to truncate to.(string): Returns the truncated string.
-_.trunc('hi-diddly-ho there, neighborino');// => 'hi-diddly-ho there, neighbo...' _.trunc('hi-diddly-ho there, neighborino', 24);// => 'hi-diddly-ho there, n...' _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' '});// => 'hi-diddly-ho there,...' _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/});// => 'hi-diddly-ho there...' _.trunc('hi-diddly-ho there, neighborino', { 'omission': ' [...]'});// => 'hi-diddly-ho there, neig [...]'
_.unescape([string=''])
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.
[string='']
(string): The string to unescape.(string): Returns the unescaped string.
-_.unescape('fred, barney, & pebbles');// => 'fred, barney, & pebbles'
_.words([string=''], [pattern])
Splits string
into an array of its words.
[string='']
(string): The string to inspect.[pattern]
(RegExp|string): The pattern to match words.(Array): Returns the words of string
.
_.words('fred, barney, & pebbles');// => ['fred', 'barney', 'pebbles'] _.words('fred, barney, & pebbles', /[^, ]+/g);// => ['fred', 'barney', '&', 'pebbles']
“Utility” Methods
_.attempt(func)
Attempts to invoke func
, returning either the result or the caught error
-object. Any additional arguments are provided to func
when it's invoked.
func
(Function): The function to attempt.(*): Returns the func
result or error object.
// avoid throwing errors for invalid selectorsvar elements = _.attempt(function(selector) { return document.querySelectorAll(selector);}, '>_>'); if (_.isError(elements)) { elements = [];}
_.callback([func=_.identity], [thisArg])
Creates a function that invokes func
with the this
binding of thisArg
-and arguments of the created function. If func
is a property name the
-created callback returns the property value for a given element. If func
-is an object the created callback returns true
for elements that contain
-the equivalent object properties, otherwise it returns false
.
_.iteratee
-[func=_.identity]
(*): The value to convert to a callback.[thisArg]
(*): The this
binding of func
.(Function): Returns the callback.
-var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }]; // wrap to create custom callback shorthands_.callback = _.wrap(_.callback, function(callback, func, thisArg) { var match = /^(.+?)__([gl]t)(.+)$/.exec(func); if (!match) { return callback(func, thisArg); } return function(object) { return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; };}); _.filter(users, 'age__gt36');// => [{ 'user': 'fred', 'age': 40 }]
_.constant(value)
Creates a function that returns value
.
value
(*): The value to return from the new function.(Function): Returns the new function.
-var object = { 'user': 'fred' };var getter = _.constant(object); getter() === object;// => true
_.identity(value)
This method returns the first argument provided to it.
-value
(*): Any value.(*): Returns value
.
var object = { 'user': 'fred' }; _.identity(object) === object;// => true
_.matches(source)
Creates a function that performs a deep comparison between a given object
-and source
, returning true
if the given object has equivalent property
-values, else false
.
-
-
-Note: This method supports comparing arrays, booleans, Date
objects,
-numbers, Object
objects, regexes, and strings. Objects are compared by
-their own, not inherited, enumerable properties. For comparing a single
-own or inherited property value see _.matchesProperty
.
source
(Object): The object of property values to match.(Function): Returns the new function.
-var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }]; _.filter(users, _.matches({ 'age': 40, 'active': false }));// => [{ 'user': 'fred', 'age': 40, 'active': false }]
_.matchesProperty(path, srcValue)
Creates a function that compares the property value of path
on a given
-object to value
.
-
-
-Note: This method supports comparing arrays, booleans, Date
objects,
-numbers, Object
objects, regexes, and strings. Objects are compared by
-their own, not inherited, enumerable properties.
path
(Array|string): The path of the property to get.srcValue
(*): The value to match.(Function): Returns the new function.
-var users = [ { 'user': 'barney' }, { 'user': 'fred' }]; _.find(users, _.matchesProperty('user', 'fred'));// => { 'user': 'fred' }
_.method(path, [args])
Creates a function that invokes the method at path
on a given object.
-Any additional arguments are provided to the invoked method.
path
(Array|string): The path of the method to invoke.[args]
(...*): The arguments to invoke the method with.(Function): Returns the new function.
-var objects = [ { 'a': { 'b': { 'c': _.constant(2) } } }, { 'a': { 'b': { 'c': _.constant(1) } } }]; _.map(objects, _.method('a.b.c'));// => [2, 1] _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');// => [1, 2]
_.methodOf(object, [args])
The opposite of _.method
; this method creates a function that invokes
-the method at a given path on object
. Any additional arguments are
-provided to the invoked method.
object
(Object): The object to query.[args]
(...*): The arguments to invoke the method with.(Function): Returns the new function.
-var array = _.times(3, _.constant), object = { 'a': array, 'b': array, 'c': array }; _.map(['a[2]', 'c[0]'], _.methodOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.methodOf(object));// => [2, 0]
_.mixin([object=lodash], source, [options])
Adds all own enumerable function properties of a source object to the
-destination object. If object
is a function then methods are added to
-its prototype as well.
-
-
-Note: Use _.runInContext
to create a pristine lodash
function to
-avoid conflicts caused by modifying the original.
[object=lodash]
(Function|Object): The destination object.source
(Object): The object of functions to add.[options]
(Object): The options object.[options.chain=true]
(boolean): Specify whether the functions added are chainable.(*): Returns object
.
function vowels(string) { return _.filter(string, function(v) { return /[aeiou]/i.test(v); });} _.mixin({ 'vowels': vowels });_.vowels('fred');// => ['e'] _('fred').vowels().value();// => ['e'] _.mixin({ 'vowels': vowels }, { 'chain': false });_('fred').vowels();// => ['e']
_.noConflict()
Reverts the _
variable to its previous value and returns a reference to
-the lodash
function.
(Function): Returns the lodash
function.
var lodash = _.noConflict();
_.noop()
A no-operation function that returns undefined
regardless of the
-arguments it receives.
var object = { 'user': 'fred' }; _.noop(object) === undefined;// => true
_.property(path)
Creates a function that returns the property value at path
on a
-given object.
path
(Array|string): The path of the property to get.(Function): Returns the new function.
-var objects = [ { 'a': { 'b': { 'c': 2 } } }, { 'a': { 'b': { 'c': 1 } } }]; _.map(objects, _.property('a.b.c'));// => [2, 1] _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');// => [1, 2]
_.propertyOf(object)
The opposite of _.property
; this method creates a function that returns
-the property value at a given path on object
.
object
(Object): The object to query.(Function): Returns the new function.
-var array = [0, 1, 2], object = { 'a': array, 'b': array, 'c': array }; _.map(['a[2]', 'c[0]'], _.propertyOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.propertyOf(object));// => [2, 0]
_.range([start=0], end, [step=1])
Creates an array of numbers (positive and/or negative) progressing from
-start
up to, but not including, end
. If end
is not specified it's
-set to start
with start
then set to 0
. If end
is less than start
-a zero-length range is created unless a negative step
is specified.
[start=0]
(number): The start of the range.end
(number): The end of the range.[step=1]
(number): The value to increment or decrement by.(Array): Returns the new array of numbers.
-_.range(4);// => [0, 1, 2, 3] _.range(1, 5);// => [1, 2, 3, 4] _.range(0, 20, 5);// => [0, 5, 10, 15] _.range(0, -4, -1);// => [0, -1, -2, -3] _.range(1, 4, 0);// => [1, 1, 1] _.range(0);// => []
_.runInContext([context=root])
Create a new pristine lodash
function using the given context
object.
[context=root]
(Object): The context object.(Function): Returns a new lodash
function.
_.mixin({ 'foo': _.constant('foo') }); var lodash = _.runInContext();lodash.mixin({ 'bar': lodash.constant('bar') }); _.isFunction(_.foo);// => true_.isFunction(_.bar);// => false lodash.isFunction(lodash.foo);// => falselodash.isFunction(lodash.bar);// => true // using `context` to mock `Date#getTime` use in `_.now`var mock = _.runInContext({ 'Date': function() { return { 'getTime': getTimeMock }; }}); // or creating a suped-up `defer` in Node.jsvar defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
_.times(n, [iteratee=_.identity], [thisArg])
Invokes the iteratee function n
times, returning an array of the results
-of each invocation. The iteratee
is bound to thisArg
and invoked with
-one argument; (index).
n
(number): The number of times to invoke iteratee
.[iteratee=_.identity]
(Function): The function invoked per iteration.[thisArg]
(*): The this
binding of iteratee
.(Array): Returns the array of results.
-var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));// => [3, 6, 4] _.times(3, function(n) { mage.castSpell(n);});// => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` _.times(3, function(n) { this.cast(n);}, mage);// => also invokes `mage.castSpell(n)` three times
Array
_.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
Collection
_.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
Date
_.now
Function
_.after
_.ary
_.before
_.bind
_.bindKey
_.curry
_.curryRight
_.debounce
_.defer
_.delay
_.flip
_.memoize
_.negate
_.once
_.overArgs
_.partial
_.partialRight
_.rearg
_.rest
_.spread
_.throttle
_.unary
_.wrap
Lang
_.castArray
_.clone
_.cloneDeep
_.cloneDeepWith
_.cloneWith
_.conformsTo
_.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
Math
Object
_.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
Seq
String
_.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
Util
_.attempt
_.bindAll
_.cond
_.conforms
_.constant
_.defaultTo
_.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
Properties
Methods
“Array” Methods
_.chunk(array, [size=1])
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
-array
(Array): The array to process.[size=1]
(number): The length of each chunk(Array): Returns the new array of chunks.
-_.chunk(['a', 'b', 'c', 'd'], 2);// => [['a', 'b'], ['c', 'd']] _.chunk(['a', 'b', 'c', 'd'], 3);// => [['a', 'b', 'c'], ['d']]
_.compact(array)
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]
_.concat(array, [values])
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]]); console.log(other);// => [1, 2, 3, [4]] console.log(array);// => [1]
_.difference(array, [values])
Creates an array of array
values not included in the other given arrays
-using SameValueZero
-for equality comparisons. The order and references of result values are
-determined by the first array.
-
-
-Note: Unlike _.pullAll
, this method returns a new array.
0.1.0
-array
(Array): The array to inspect.[values]
(...Array): The values to exclude.(Array): Returns the new array of filtered values.
-_.difference([2, 1], [2, 3]);// => [1]
_.differenceBy(array, [values], [iteratee=_.identity])
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. The order and references of result values are
-determined by the first array. The iteratee is invoked with one argument:
-(value).
-
-
-Note: Unlike _.pullAllBy
, this method returns a new array.
4.0.0
-array
(Array): The array to inspect.[values]
(...Array): The values to exclude.[iteratee=_.identity]
(Function): The iteratee invoked per element.(Array): Returns the new array of filtered values.
-_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);// => [1.2] // The `_.property` iteratee shorthand._.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');// => [{ 'x': 2 }]
_.differenceWith(array, [values], [comparator])
This method is like _.difference
except that it accepts comparator
-which is invoked to compare elements of array
to values
. The order and
-references of result values are determined by the first array. The comparator
-is invoked with two arguments: (arrVal, othVal).
-
-
-Note: Unlike _.pullAllWith
, this method returns a new array.
4.0.0
-array
(Array): The array to inspect.[values]
(...Array): The values to exclude.[comparator]
(Function): The comparator invoked per element.(Array): Returns the new array of filtered values.
-var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);// => [{ 'x': 2, 'y': 1 }]
_.drop(array, [n=1])
Creates a slice of array
with n
elements dropped from the beginning.
0.5.0
-array
(Array): The array to query.[n=1]
(number): The number of elements to drop.(Array): Returns the slice of array
.
_.drop([1, 2, 3]);// => [2, 3] _.drop([1, 2, 3], 2);// => [3] _.drop([1, 2, 3], 5);// => [] _.drop([1, 2, 3], 0);// => [1, 2, 3]
_.dropRight(array, [n=1])
Creates a slice of array
with n
elements dropped from the end.
3.0.0
-array
(Array): The array to query.[n=1]
(number): The number of elements to drop.(Array): Returns the slice of array
.
_.dropRight([1, 2, 3]);// => [1, 2] _.dropRight([1, 2, 3], 2);// => [1] _.dropRight([1, 2, 3], 5);// => [] _.dropRight([1, 2, 3], 0);// => [1, 2, 3]
_.dropRightWhile(array, [predicate=_.identity])
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
-array
(Array): The array to query.[predicate=_.identity]
(Function): The function invoked per iteration.(Array): Returns the slice of array
.
var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': false }]; _.dropRightWhile(users, function(o) { return !o.active; });// => objects for ['barney'] // The `_.matches` iteratee shorthand._.dropRightWhile(users, { 'user': 'pebbles', 'active': false });// => objects for ['barney', 'fred'] // The `_.matchesProperty` iteratee shorthand._.dropRightWhile(users, ['active', false]);// => objects for ['barney'] // The `_.property` iteratee shorthand._.dropRightWhile(users, 'active');// => objects for ['barney', 'fred', 'pebbles']
_.dropWhile(array, [predicate=_.identity])
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
-array
(Array): The array to query.[predicate=_.identity]
(Function): The function invoked per iteration.(Array): Returns the slice of array
.
var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': true }]; _.dropWhile(users, function(o) { return !o.active; });// => objects for ['pebbles'] // The `_.matches` iteratee shorthand._.dropWhile(users, { 'user': 'barney', 'active': false });// => objects for ['fred', 'pebbles'] // The `_.matchesProperty` iteratee shorthand._.dropWhile(users, ['active', false]);// => objects for ['pebbles'] // The `_.property` iteratee shorthand._.dropWhile(users, 'active');// => objects for ['barney', 'fred', 'pebbles']
_.fill(array, value, [start=0], [end=array.length])
Fills elements of array
with value
from start
up to, but not
-including, end
.
-
-
-Note: This method mutates array
.
3.2.0
-array
(Array): The array to fill.value
(*): The value to fill array
with.[start=0]
(number): The start position.[end=array.length]
(number): The end position.(Array): Returns array
.
var array = [1, 2, 3]; _.fill(array, 'a');console.log(array);// => ['a', 'a', 'a'] _.fill(Array(3), 2);// => [2, 2, 2] _.fill([4, 6, 8, 10], '*', 1, 3);// => [4, '*', '*', 10]
_.findIndex(array, [predicate=_.identity], [fromIndex=0])
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
-array
(Array): The array to inspect.[predicate=_.identity]
(Function): The function invoked per iteration.[fromIndex=0]
(number): The index to search from.(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(users, function(o) { return o.user == 'barney'; });// => 0 // The `_.matches` iteratee shorthand._.findIndex(users, { 'user': 'fred', 'active': false });// => 1 // The `_.matchesProperty` iteratee shorthand._.findIndex(users, ['active', false]);// => 0 // The `_.property` iteratee shorthand._.findIndex(users, 'active');// => 2
_.findLastIndex(array, [predicate=_.identity], [fromIndex=array.length-1])
This method is like _.findIndex
except that it iterates over elements
-of collection
from right to left.
2.0.0
-array
(Array): The array to inspect.[predicate=_.identity]
(Function): The function invoked per iteration.[fromIndex=array.length-1]
(number): The index to search from.(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(users, function(o) { return o.user == 'pebbles'; });// => 2 // The `_.matches` iteratee shorthand._.findLastIndex(users, { 'user': 'barney', 'active': true });// => 0 // The `_.matchesProperty` iteratee shorthand._.findLastIndex(users, ['active', false]);// => 2 // The `_.property` iteratee shorthand._.findLastIndex(users, 'active');// => 0
_.flatten(array)
Flattens 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]
_.flattenDeep(array)
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]
_.flattenDepth(array, [depth=1])
Recursively flatten array
up to depth
times.
4.4.0
-array
(Array): The array to flatten.[depth=1]
(number): The maximum recursion depth.(Array): Returns the new flattened array.
-var array = [1, [2, [3, [4]], 5]]; _.flattenDepth(array, 1);// => [1, 2, [3, [4]], 5] _.flattenDepth(array, 2);// => [1, 2, 3, [4], 5]
_.fromPairs(pairs)
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([['a', 1], ['b', 2]]);// => { 'a': 1, 'b': 2 }
_.head(array)
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([]);// => undefined
_.indexOf(array, value, [fromIndex=0])
Gets the index at which the first occurrence of value
is found in array
-using SameValueZero
-for equality comparisons. If fromIndex
is negative, it's used as the
-offset from the end of array
.
0.1.0
-array
(Array): The array to inspect.value
(*): The value to search for.[fromIndex=0]
(number): The index to search from.(number): Returns the index of the matched value, else -1
.
_.indexOf([1, 2, 1, 2], 2);// => 1 // Search from the `fromIndex`._.indexOf([1, 2, 1, 2], 2, 2);// => 3
_.initial(array)
Gets 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]
_.intersection([arrays])
Creates an array of unique values that are included in all given arrays
-using SameValueZero
-for equality comparisons. The order and references of result values are
-determined by the first array.
0.1.0
-[arrays]
(...Array): The arrays to inspect.(Array): Returns the new array of intersecting values.
-_.intersection([2, 1], [2, 3]);// => [2]
_.intersectionBy([arrays], [iteratee=_.identity])
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. The order and references of result values are
-determined by the first array. The iteratee is invoked with one argument:
-(value).
4.0.0
-[arrays]
(...Array): The arrays to inspect.[iteratee=_.identity]
(Function): The iteratee invoked per element.(Array): Returns the new array of intersecting values.
-_.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);// => [2.1] // The `_.property` iteratee shorthand._.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }]
_.intersectionWith([arrays], [comparator])
This method is like _.intersection
except that it accepts comparator
-which is invoked to compare elements of arrays
. The order and references
-of result values are determined by the first array. The comparator is
-invoked with two arguments: (arrVal, othVal).
4.0.0
-[arrays]
(...Array): The arrays to inspect.[comparator]
(Function): The comparator invoked per element.(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(objects, others, _.isEqual);// => [{ 'x': 1, 'y': 2 }]
_.join(array, [separator=','])
Converts all elements in array
into a string separated by separator
.
4.0.0
-array
(Array): The array to convert.[separator=',']
(string): The element separator.(string): Returns the joined string.
-_.join(['a', 'b', 'c'], '~');// => 'a~b~c'
_.last(array)
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]);// => 3
_.lastIndexOf(array, value, [fromIndex=array.length-1])
This method is like _.indexOf
except that it iterates over elements of
-array
from right to left.
0.1.0
-array
(Array): The array to inspect.value
(*): The value to search for.[fromIndex=array.length-1]
(number): The index to search from.(number): Returns the index of the matched value, else -1
.
_.lastIndexOf([1, 2, 1, 2], 2);// => 3 // Search from the `fromIndex`._.lastIndexOf([1, 2, 1, 2], 2, 2);// => 1
_.nth(array, [n=0])
Gets the element at index n
of array
. If n
is negative, the nth
-element from the end is returned.
4.11.0
-array
(Array): The array to query.[n=0]
(number): The index of the element to return.(*): Returns the nth element of array
.
var array = ['a', 'b', 'c', 'd']; _.nth(array, 1);// => 'b' _.nth(array, -2);// => 'c';
_.pull(array, [values])
Removes all given values from array
using
-SameValueZero
-for equality comparisons.
-
-
-Note: Unlike _.without
, this method mutates array
. Use _.remove
-to remove elements from an array by predicate.
2.0.0
-array
(Array): The array to modify.[values]
(...*): The values to remove.(Array): Returns array
.
var array = ['a', 'b', 'c', 'a', 'b', 'c']; _.pull(array, 'a', 'c');console.log(array);// => ['b', 'b']
_.pullAll(array, values)
This method is like _.pull
except that it accepts an array of values to remove.
-
-
-Note: Unlike _.difference
, this method mutates array
.
4.0.0
-array
(Array): The array to modify.values
(Array): The values to remove.(Array): Returns array
.
var array = ['a', 'b', 'c', 'a', 'b', 'c']; _.pullAll(array, ['a', 'c']);console.log(array);// => ['b', 'b']
_.pullAllBy(array, values, [iteratee=_.identity])
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).
-
-
-Note: Unlike _.differenceBy
, this method mutates array
.
4.0.0
-array
(Array): The array to modify.values
(Array): The values to remove.[iteratee=_.identity]
(Function): The iteratee invoked per element.(Array): Returns array
.
var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');console.log(array);// => [{ 'x': 2 }]
_.pullAllWith(array, values, [comparator])
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).
-
-
-Note: Unlike _.differenceWith
, this method mutates array
.
4.6.0
-array
(Array): The array to modify.values
(Array): The values to remove.[comparator]
(Function): The comparator invoked per element.(Array): Returns array
.
var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);console.log(array);// => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
_.pullAt(array, [indexes])
Removes elements from array
corresponding to indexes
and returns an
-array of removed elements.
-
-
-Note: Unlike _.at
, this method mutates array
.
3.0.0
-array
(Array): The array to modify.[indexes]
(...(number|number[])): The indexes of elements to remove.(Array): Returns the new array of removed elements.
-var array = ['a', 'b', 'c', 'd'];var pulled = _.pullAt(array, [1, 3]); console.log(array);// => ['a', 'c'] console.log(pulled);// => ['b', 'd']
_.remove(array, [predicate=_.identity])
Removes all elements from array
that predicate
returns truthy for
-and returns an array of the removed elements. The predicate is invoked
-with three arguments: (value, index, array).
-
-
-Note: Unlike _.filter
, this method mutates array
. Use _.pull
-to pull elements from an array by value.
2.0.0
-array
(Array): The array to modify.[predicate=_.identity]
(Function): The function invoked per iteration.(Array): Returns the new array of removed elements.
-var array = [1, 2, 3, 4];var evens = _.remove(array, function(n) { return n % 2 == 0;}); console.log(array);// => [1, 3] console.log(evens);// => [2, 4]
_.reverse(array)
Reverses array
so that the first element becomes the last, the second
-element becomes the second to last, and so on.
-
-
-Note: This method mutates array
and is based on
-Array#reverse
.
4.0.0
-array
(Array): The array to modify.(Array): Returns array
.
var array = [1, 2, 3]; _.reverse(array);// => [3, 2, 1] console.log(array);// => [3, 2, 1]
_.slice(array, [start=0], [end=array.length])
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
-array
(Array): The array to slice.[start=0]
(number): The start position.[end=array.length]
(number): The end position.(Array): Returns the slice of array
.
_.sortedIndex(array, value)
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
-array
(Array): The sorted array to inspect.value
(*): The value to evaluate.(number): Returns the index at which value
should be inserted into array
.
_.sortedIndex([30, 50], 40);// => 1
_.sortedIndexBy(array, value, [iteratee=_.identity])
This method is like _.sortedIndex
except that it accepts iteratee
-which is invoked for value
and each element of array
to compute their
-sort ranking. The iteratee is invoked with one argument: (value).
4.0.0
-array
(Array): The sorted array to inspect.value
(*): The value to evaluate.[iteratee=_.identity]
(Function): The iteratee invoked per element.(number): Returns the index at which value
should be inserted into array
.
var objects = [{ 'x': 4 }, { 'x': 5 }]; _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });// => 0 // The `_.property` iteratee shorthand._.sortedIndexBy(objects, { 'x': 4 }, 'x');// => 0
_.sortedIndexOf(array, value)
This method is like _.indexOf
except that it performs a binary
-search on a sorted array
.
4.0.0
-array
(Array): The array to inspect.value
(*): The value to search for.(number): Returns the index of the matched value, else -1
.
_.sortedIndexOf([4, 5, 5, 5, 6], 5);// => 1
_.sortedLastIndex(array, value)
This method is like _.sortedIndex
except that it returns the highest
-index at which value
should be inserted into array
in order to
-maintain its sort order.
3.0.0
-array
(Array): The sorted array to inspect.value
(*): The value to evaluate.(number): Returns the index at which value
should be inserted into array
.
_.sortedLastIndex([4, 5, 5, 5, 6], 5);// => 4
_.sortedLastIndexBy(array, value, [iteratee=_.identity])
This method is like _.sortedLastIndex
except that it accepts iteratee
-which is invoked for value
and each element of array
to compute their
-sort ranking. The iteratee is invoked with one argument: (value).
4.0.0
-array
(Array): The sorted array to inspect.value
(*): The value to evaluate.[iteratee=_.identity]
(Function): The iteratee invoked per element.(number): Returns the index at which value
should be inserted into array
.
var objects = [{ 'x': 4 }, { 'x': 5 }]; _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });// => 1 // The `_.property` iteratee shorthand._.sortedLastIndexBy(objects, { 'x': 4 }, 'x');// => 1
_.sortedLastIndexOf(array, value)
This method is like _.lastIndexOf
except that it performs a binary
-search on a sorted array
.
4.0.0
-array
(Array): The array to inspect.value
(*): The value to search for.(number): Returns the index of the matched value, else -1
.
_.sortedLastIndexOf([4, 5, 5, 5, 6], 5);// => 3
_.sortedUniq(array)
This 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]
_.sortedUniqBy(array, [iteratee])
This method is like _.uniqBy
except that it's designed and optimized
-for sorted arrays.
4.0.0
-array
(Array): The array to inspect.[iteratee]
(Function): The iteratee invoked per element.(Array): Returns the new duplicate free array.
-_.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);// => [1.1, 2.3]
_.tail(array)
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]
_.take(array, [n=1])
Creates a slice of array
with n
elements taken from the beginning.
0.1.0
-array
(Array): The array to query.[n=1]
(number): The number of elements to take.(Array): Returns the slice of array
.
_.take([1, 2, 3]);// => [1] _.take([1, 2, 3], 2);// => [1, 2] _.take([1, 2, 3], 5);// => [1, 2, 3] _.take([1, 2, 3], 0);// => []
_.takeRight(array, [n=1])
Creates a slice of array
with n
elements taken from the end.
3.0.0
-array
(Array): The array to query.[n=1]
(number): The number of elements to take.(Array): Returns the slice of array
.
_.takeRight([1, 2, 3]);// => [3] _.takeRight([1, 2, 3], 2);// => [2, 3] _.takeRight([1, 2, 3], 5);// => [1, 2, 3] _.takeRight([1, 2, 3], 0);// => []
_.takeRightWhile(array, [predicate=_.identity])
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
-array
(Array): The array to query.[predicate=_.identity]
(Function): The function invoked per iteration.(Array): Returns the slice of array
.
var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': false }]; _.takeRightWhile(users, function(o) { return !o.active; });// => objects for ['fred', 'pebbles'] // The `_.matches` iteratee shorthand._.takeRightWhile(users, { 'user': 'pebbles', 'active': false });// => objects for ['pebbles'] // The `_.matchesProperty` iteratee shorthand._.takeRightWhile(users, ['active', false]);// => objects for ['fred', 'pebbles'] // The `_.property` iteratee shorthand._.takeRightWhile(users, 'active');// => []
_.takeWhile(array, [predicate=_.identity])
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
-array
(Array): The array to query.[predicate=_.identity]
(Function): The function invoked per iteration.(Array): Returns the slice of array
.
var users = [ { 'user': 'barney', 'active': false }, { 'user': 'fred', 'active': false }, { 'user': 'pebbles', 'active': true }]; _.takeWhile(users, function(o) { return !o.active; });// => objects for ['barney', 'fred'] // The `_.matches` iteratee shorthand._.takeWhile(users, { 'user': 'barney', 'active': false });// => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand._.takeWhile(users, ['active', false]);// => objects for ['barney', 'fred'] // The `_.property` iteratee shorthand._.takeWhile(users, 'active');// => []
_.union([arrays])
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.(Array): Returns the new array of combined values.
-_.union([2], [1, 2]);// => [2, 1]
_.unionBy([arrays], [iteratee=_.identity])
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. Result values are chosen from the first
-array in which the value occurs. The iteratee is invoked with one argument:
-(value).
4.0.0
-[arrays]
(...Array): The arrays to inspect.[iteratee=_.identity]
(Function): The iteratee invoked per element.(Array): Returns the new array of combined values.
-_.unionBy([2.1], [1.2, 2.3], Math.floor);// => [2.1, 1.2] // The `_.property` iteratee shorthand._.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }, { 'x': 2 }]
_.unionWith([arrays], [comparator])
This method is like _.union
except that it accepts comparator
which
-is invoked to compare elements of arrays
. Result values are chosen from
-the first array in which the value occurs. The comparator is invoked
-with two arguments: (arrVal, othVal).
4.0.0
-[arrays]
(...Array): The arrays to inspect.[comparator]
(Function): The comparator invoked per element.(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(objects, others, _.isEqual);// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
_.uniq(array)
Creates a duplicate-free version of an array, using
-SameValueZero
-for equality comparisons, in which only the first occurrence of each element
-is kept. The order of result values is determined by the order they occur
-in the array.
0.1.0
-array
(Array): The array to inspect.(Array): Returns the new duplicate free array.
-_.uniq([2, 1, 2]);// => [2, 1]
_.uniqBy(array, [iteratee=_.identity])
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 order of result values is determined by the
-order they occur in the array. The iteratee is invoked with one argument:
-(value).
4.0.0
-array
(Array): The array to inspect.[iteratee=_.identity]
(Function): The iteratee invoked per element.(Array): Returns the new duplicate free array.
-_.uniqBy([2.1, 1.2, 2.3], Math.floor);// => [2.1, 1.2] // The `_.property` iteratee shorthand._.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 1 }, { 'x': 2 }]
_.uniqWith(array, [comparator])
This method is like _.uniq
except that it accepts comparator
which
-is invoked to compare elements of array
. The order of result values is
-determined by the order they occur in the array.The comparator is invoked
-with two arguments: (arrVal, othVal).
4.0.0
-array
(Array): The array to inspect.[comparator]
(Function): The comparator invoked per element.(Array): Returns the new duplicate free array.
-var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; _.uniqWith(objects, _.isEqual);// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
_.unzip(array)
This method is like _.zip
except that it accepts an array of grouped
-elements and creates an array regrouping the elements to their pre-zip
-configuration.
1.2.0
-array
(Array): The array of grouped elements to process.(Array): Returns the new array of regrouped elements.
-var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);// => [['a', 1, true], ['b', 2, false]] _.unzip(zipped);// => [['a', 'b'], [1, 2], [true, false]]
_.unzipWith(array, [iteratee=_.identity])
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
-array
(Array): The array of grouped elements to process.[iteratee=_.identity]
(Function): The function to combine regrouped values.(Array): Returns the new array of regrouped elements.
-var zipped = _.zip([1, 2], [10, 20], [100, 200]);// => [[1, 10, 100], [2, 20, 200]] _.unzipWith(zipped, _.add);// => [3, 30, 300]
_.without(array, [values])
Creates an array excluding all given values using
-SameValueZero
-for equality comparisons.
-
-
-Note: Unlike _.pull
, this method returns a new array.
0.1.0
-array
(Array): The array to inspect.[values]
(...*): The values to exclude.(Array): Returns the new array of filtered values.
-_.without([2, 1, 2, 3], 1, 2);// => [3]
_.xor([arrays])
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.(Array): Returns the new array of filtered values.
-_.xor([2, 1], [2, 3]);// => [1, 3]
_.xorBy([arrays], [iteratee=_.identity])
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 order of result values is determined
-by the order they occur in the arrays. The iteratee is invoked with one
-argument: (value).
4.0.0
-[arrays]
(...Array): The arrays to inspect.[iteratee=_.identity]
(Function): The iteratee invoked per element.(Array): Returns the new array of filtered values.
-_.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);// => [1.2, 3.4] // The `_.property` iteratee shorthand._.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');// => [{ 'x': 2 }]
_.xorWith([arrays], [comparator])
This method is like _.xor
except that it accepts comparator
which is
-invoked to compare elements of arrays
. The order of result values is
-determined by the order they occur in the arrays. The comparator is invoked
-with two arguments: (arrVal, othVal).
4.0.0
-[arrays]
(...Array): The arrays to inspect.[comparator]
(Function): The comparator invoked per element.(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(objects, others, _.isEqual);// => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
_.zip([arrays])
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.(Array): Returns the new array of grouped elements.
-_.zip(['a', 'b'], [1, 2], [true, false]);// => [['a', 1, true], ['b', 2, false]]
_.zipObject([props=[]], [values=[]])
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 }
_.zipObjectDeep([props=[]], [values=[]])
This method is like _.zipObject
except that it supports property paths.
4.1.0
-[props=[]]
(Array): The property identifiers.[values=[]]
(Array): The property values.(Object): Returns the new object.
-_.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
_.zipWith([arrays], [iteratee=_.identity])
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
-[arrays]
(...Array): The arrays to process.[iteratee=_.identity]
(Function): The function to combine grouped values.(Array): Returns the new array of grouped elements.
-_.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { return a + b + c;});// => [111, 222]
“Collection” Methods
_.countBy(collection, [iteratee=_.identity])
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
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The iteratee to transform keys.(Object): Returns the composed aggregate object.
-_.countBy([6.1, 4.2, 6.3], Math.floor);// => { '4': 1, '6': 2 } // The `_.property` iteratee shorthand._.countBy(['one', 'two', 'three'], 'length');// => { '3': 2, '5': 1 }
_.every(collection, [predicate=_.identity])
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).
-
-
-Note: This method returns true
for
-empty collections because
-everything is true of
-elements of empty collections.
0.1.0
-collection
(Array|Object): The collection to iterate over.[predicate=_.identity]
(Function): The function invoked per iteration.(boolean): Returns true
if all elements pass the predicate check, else false
.
_.every([true, 1, null, 'yes'], Boolean);// => false var users = [ { 'user': 'barney', 'age': 36, 'active': false }, { 'user': 'fred', 'age': 40, 'active': false }]; // The `_.matches` iteratee shorthand._.every(users, { 'user': 'barney', 'active': false });// => false // The `_.matchesProperty` iteratee shorthand._.every(users, ['active', false]);// => true // The `_.property` iteratee shorthand._.every(users, 'active');// => false
_.filter(collection, [predicate=_.identity])
Iterates over elements of collection
, returning an array of all elements
-predicate
returns truthy for. The predicate is invoked with three
-arguments: (value, index|key, collection).
-
-
-Note: Unlike _.remove
, this method returns a new array.
0.1.0
-collection
(Array|Object): The collection to iterate over.[predicate=_.identity]
(Function): The function invoked per iteration.(Array): Returns the new filtered array.
-var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }]; _.filter(users, function(o) { return !o.active; });// => objects for ['fred'] // The `_.matches` iteratee shorthand._.filter(users, { 'age': 36, 'active': true });// => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand._.filter(users, ['active', false]);// => objects for ['fred'] // The `_.property` iteratee shorthand._.filter(users, 'active');// => objects for ['barney']
_.find(collection, [predicate=_.identity], [fromIndex=0])
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
-collection
(Array|Object): The collection to inspect.[predicate=_.identity]
(Function): The function invoked per iteration.[fromIndex=0]
(number): The index to search from.(*): 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(users, function(o) { return o.age < 40; });// => object for 'barney' // The `_.matches` iteratee shorthand._.find(users, { 'age': 1, 'active': true });// => object for 'pebbles' // The `_.matchesProperty` iteratee shorthand._.find(users, ['active', false]);// => object for 'fred' // The `_.property` iteratee shorthand._.find(users, 'active');// => object for 'barney'
_.findLast(collection, [predicate=_.identity], [fromIndex=collection.length-1])
This method is like _.find
except that it iterates over elements of
-collection
from right to left.
2.0.0
-collection
(Array|Object): The collection to inspect.[predicate=_.identity]
(Function): The function invoked per iteration.[fromIndex=collection.length-1]
(number): The index to search from.(*): Returns the matched element, else undefined
.
_.findLast([1, 2, 3, 4], function(n) { return n % 2 == 1;});// => 3
_.flatMap(collection, [iteratee=_.identity])
Creates 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
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Array): Returns the new flattened array.
-function duplicate(n) { return [n, n];} _.flatMap([1, 2], duplicate);// => [1, 1, 2, 2]
_.flatMapDeep(collection, [iteratee=_.identity])
This method is like _.flatMap
except that it recursively flattens the
-mapped results.
4.7.0
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Array): Returns the new flattened array.
-function duplicate(n) { return [[[n, n]]];} _.flatMapDeep([1, 2], duplicate);// => [1, 1, 2, 2]
_.flatMapDepth(collection, [iteratee=_.identity], [depth=1])
This method is like _.flatMap
except that it recursively flattens the
-mapped results up to depth
times.
4.7.0
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[depth=1]
(number): The maximum recursion depth.(Array): Returns the new flattened array.
-function duplicate(n) { return [[[n, n]]];} _.flatMapDepth([1, 2], duplicate, 2);// => [[1, 1], [2, 2]]
_.forEach(collection, [iteratee=_.identity])
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
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(*): Returns collection
.
_.forEach([1, 2], function(value) { console.log(value);});// => Logs `1` then `2`. _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { console.log(key);});// => Logs 'a' then 'b' (iteration order is not guaranteed).
_.forEachRight(collection, [iteratee=_.identity])
This method is like _.forEach
except that it iterates over elements of
-collection
from right to left.
2.0.0
-_.eachRight
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(*): Returns collection
.
_.forEachRight([1, 2], function(value) { console.log(value);});// => Logs `2` then `1`.
_.groupBy(collection, [iteratee=_.identity])
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
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The iteratee to transform keys.(Object): Returns the composed aggregate object.
-_.groupBy([6.1, 4.2, 6.3], Math.floor);// => { '4': [4.2], '6': [6.1, 6.3] } // The `_.property` iteratee shorthand._.groupBy(['one', 'two', 'three'], 'length');// => { '3': ['one', 'two'], '5': ['three'] }
_.includes(collection, value, [fromIndex=0])
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
-collection
(Array|Object|string): The collection to inspect.value
(*): The value to search for.[fromIndex=0]
(number): The index to search from.(boolean): Returns true
if value
is found, else false
.
_.includes([1, 2, 3], 1);// => true _.includes([1, 2, 3], 1, 2);// => false _.includes({ 'a': 1, 'b': 2 }, 1);// => true _.includes('abcd', 'bc');// => true
_.invokeMap(collection, path, [args])
Invokes the method at path
of each element in collection
, returning
-an array of the results of each invoked method. Any additional arguments
-are provided to each invoked method. If path
is a function, it's invoked
-for, and this
bound to, each element in collection
.
4.0.0
-collection
(Array|Object): The collection to iterate over.path
(Array|Function|string): The path of the method to invoke or the function invoked per iteration.[args]
(...*): The arguments to invoke each method with.(Array): Returns the array of results.
-_.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');// => [[1, 5, 7], [1, 2, 3]] _.invokeMap([123, 456], String.prototype.split, '');// => [['1', '2', '3'], ['4', '5', '6']]
_.keyBy(collection, [iteratee=_.identity])
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
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The iteratee to transform keys.(Object): Returns the composed aggregate object.
-var array = [ { 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 }]; _.keyBy(array, function(o) { return String.fromCharCode(o.code);});// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } _.keyBy(array, 'dir');// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
_.map(collection, [iteratee=_.identity])
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
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Array): Returns the new mapped array.
-function square(n) { return n * n;} _.map([4, 8], square);// => [16, 64] _.map({ 'a': 4, 'b': 8 }, square);// => [16, 64] (iteration order is not guaranteed) var users = [ { 'user': 'barney' }, { 'user': 'fred' }]; // The `_.property` iteratee shorthand._.map(users, 'user');// => ['barney', 'fred']
_.orderBy(collection, [iteratees=[_.identity]], [orders])
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
-collection
(Array|Object): The collection to iterate over.[iteratees=[_.identity]]
(Array[]|Function[]|Object[]|string[]): The iteratees to sort by.[orders]
(string[]): The sort orders of iteratees
.(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(users, ['user', 'age'], ['asc', 'desc']);// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
_.partition(collection, [predicate=_.identity])
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
-collection
(Array|Object): The collection to iterate over.[predicate=_.identity]
(Function): The function invoked per iteration.(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(users, function(o) { return o.active; });// => objects for [['fred'], ['barney', 'pebbles']] // The `_.matches` iteratee shorthand._.partition(users, { 'age': 1, 'active': false });// => objects for [['pebbles'], ['barney', 'fred']] // The `_.matchesProperty` iteratee shorthand._.partition(users, ['active', false]);// => objects for [['barney', 'pebbles'], ['fred']] // The `_.property` iteratee shorthand._.partition(users, 'active');// => objects for [['fred'], ['barney', 'pebbles']]
_.reduce(collection, [iteratee=_.identity], [accumulator])
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
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[accumulator]
(*): The initial value.(*): Returns the accumulated value.
-_.reduce([1, 2], function(sum, n) { return sum + n;}, 0);// => 3 _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { (result[value] || (result[value] = [])).push(key); return result;}, {});// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
_.reduceRight(collection, [iteratee=_.identity], [accumulator])
This method is like _.reduce
except that it iterates over elements of
-collection
from right to left.
0.1.0
-collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[accumulator]
(*): The initial value.(*): Returns the accumulated value.
-var array = [[0, 1], [2, 3], [4, 5]]; _.reduceRight(array, function(flattened, other) { return flattened.concat(other);}, []);// => [4, 5, 2, 3, 0, 1]
_.reject(collection, [predicate=_.identity])
The opposite of _.filter
; this method returns the elements of collection
-that predicate
does not return truthy for.
0.1.0
-collection
(Array|Object): The collection to iterate over.[predicate=_.identity]
(Function): The function invoked per iteration.(Array): Returns the new filtered array.
-var users = [ { 'user': 'barney', 'age': 36, 'active': false }, { 'user': 'fred', 'age': 40, 'active': true }]; _.reject(users, function(o) { return !o.active; });// => objects for ['fred'] // The `_.matches` iteratee shorthand._.reject(users, { 'age': 40, 'active': true });// => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand._.reject(users, ['active', false]);// => objects for ['fred'] // The `_.property` iteratee shorthand._.reject(users, 'active');// => objects for ['barney']
_.sample(collection)
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]);// => 2
_.sampleSize(collection, [n=1])
Gets n
random elements at unique keys from collection
up to the
-size of collection
.
4.0.0
-collection
(Array|Object): The collection to sample.[n=1]
(number): The number of elements to sample.(Array): Returns the random elements.
-_.sampleSize([1, 2, 3], 2);// => [3, 1] _.sampleSize([1, 2, 3], 4);// => [2, 3, 1]
_.shuffle(collection)
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]
_.size(collection)
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|string): The collection to inspect.(number): Returns the collection size.
-_.size([1, 2, 3]);// => 3 _.size({ 'a': 1, 'b': 2 });// => 2 _.size('pebbles');// => 7
_.some(collection, [predicate=_.identity])
Checks if predicate
returns truthy for any element of collection
.
-Iteration is stopped once predicate
returns truthy. The predicate is
-invoked with three arguments: (value, index|key, collection).
0.1.0
-collection
(Array|Object): The collection to iterate over.[predicate=_.identity]
(Function): The function invoked per iteration.(boolean): Returns true
if any element passes the predicate check, else false
.
_.some([null, 0, 'yes', false], Boolean);// => true var users = [ { 'user': 'barney', 'active': true }, { 'user': 'fred', 'active': false }]; // The `_.matches` iteratee shorthand._.some(users, { 'user': 'barney', 'active': false });// => false // The `_.matchesProperty` iteratee shorthand._.some(users, ['active', false]);// => true // The `_.property` iteratee shorthand._.some(users, 'active');// => true
_.sortBy(collection, [iteratees=[_.identity]])
Creates 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
-collection
(Array|Object): The collection to iterate over.[iteratees=[_.identity]]
(...(Function|Function[])): The iteratees to sort by.(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(users, [function(o) { return o.user; }]);// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] _.sortBy(users, ['user', 'age']);// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
“Date” Methods
_.now()
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() - stamp);}, _.now());// => Logs the number of milliseconds it took for the deferred invocation.
“Function” Methods
_.after(n, func)
The opposite of _.before
; this method creates a function that invokes
-func
once it's called n
or more times.
0.1.0
-n
(number): The number of calls before func
is invoked.func
(Function): The function to restrict.(Function): Returns the new restricted function.
-var saves = ['profile', 'settings']; var done = _.after(saves.length, function() { console.log('done saving!');}); _.forEach(saves, function(type) { asyncSave({ 'type': type, 'complete': done });});// => Logs 'done saving!' after the two async saves have completed.
_.ary(func, [n=func.length])
Creates a function that invokes func
, with up to n
arguments,
-ignoring any additional arguments.
3.0.0
-func
(Function): The function to cap arguments for.[n=func.length]
(number): The arity cap.(Function): Returns the new capped function.
-_.map(['6', '8', '10'], _.ary(parseInt, 1));// => [6, 8, 10]
_.before(n, func)
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
-n
(number): The number of calls at which func
is no longer invoked.func
(Function): The function to restrict.(Function): Returns the new restricted function.
-jQuery(element).on('click', _.before(5, addContactToList));// => Allows adding up to 4 contacts to the list.
_.bind(func, thisArg, [partials])
Creates 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
(*): The this
binding of func
.[partials]
(...*): The arguments to be partially applied.(Function): Returns the new bound function.
-function greet(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!'
_.bindKey(object, key, [partials])
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.[partials]
(...*): The arguments to be partially applied.(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!'
_.curry(func, [arity=func.length])
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.[arity=func.length]
(number): The arity of func
.(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, 3, 2]
_.curryRight(func, [arity=func.length])
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.[arity=func.length]
(number): The arity of func
.(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]
_.debounce(func, [wait=0], [options={}])
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 options
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.
-
-
-If wait
is 0
and leading
is false
, func
invocation is deferred
-until to the next tick, similar to setTimeout
with a timeout of 0
.
-
-
-See David Corbacho's article
-for details over the differences between _.debounce
and _.throttle
.
0.1.0
-func
(Function): The function to debounce.[wait=0]
(number): The number of milliseconds to delay.[options={}]
(Object): The options object.[options.leading=false]
(boolean): Specify invoking on the leading edge of the timeout.[options.maxWait]
(number): The maximum time func
is allowed to be delayed before it's invoked.[options.trailing=true]
(boolean): Specify invoking on the trailing edge of the timeout.(Function): Returns the new debounced function.
-// Avoid costly calculations while the window size is in flux.jQuery(window).on('resize', _.debounce(calculateLayout, 150)); // Invoke `sendMail` when clicked, debouncing subsequent calls.jQuery(element).on('click', _.debounce(sendMail, 300, { 'leading': true, 'trailing': false})); // Ensure `batchLog` is invoked once after 1 second of debounced calls.var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });var source = new EventSource('/stream');jQuery(source).on('message', debounced); // Cancel the trailing debounced invocation.jQuery(window).on('popstate', debounced.cancel);
_.defer(func, [args])
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.[args]
(...*): The arguments to invoke func
with.(number): Returns the timer id.
-_.defer(function(text) { console.log(text);}, 'deferred');// => Logs 'deferred' after one millisecond.
_.delay(func, wait, [args])
Invokes func
after wait
milliseconds. Any additional arguments are
-provided to func
when it's invoked.
0.1.0
-func
(Function): The function to delay.wait
(number): The number of milliseconds to delay invocation.[args]
(...*): The arguments to invoke func
with.(number): Returns the timer id.
-_.delay(function(text) { console.log(text);}, 1000, 'later');// => Logs 'later' after one second.
_.flip(func)
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']
_.memoize(func, [resolver])
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 clear
, delete
, get
, has
, and set
.
0.1.0
-func
(Function): The function to have its output memoized.[resolver]
(Function): The function to resolve the cache key.(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;
_.negate(predicate)
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([1, 2, 3, 4, 5, 6], _.negate(isEven));// => [1, 3, 5]
_.once(func)
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();// => `createApplication` is invoked once
_.overArgs(func, [transforms=[_.identity]])
Creates a function that invokes func
with its arguments transformed.
4.0.0
-func
(Function): The function to wrap.[transforms=[_.identity]]
(...(Function|Function[])): The argument transforms.(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]
_.partial(func, [partials])
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.
-function greet(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'
_.partialRight(func, [partials])
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.
-function greet(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'
_.rearg(func, indexes)
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
-func
(Function): The function to rearrange arguments for.indexes
(...(number|number[])): The arranged argument indexes.(Function): Returns the new function.
-var rearged = _.rearg(function(a, b, c) { return [a, b, c];}, [2, 0, 1]); rearged('b', 'c', 'a')// => ['a', 'b', 'c']
_.rest(func, [start=func.length-1])
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.[start=func.length-1]
(number): The start position of the rest parameter.(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'
_.spread(func, [start=0])
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.[start=0]
(number): The start position of the spread.(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 76
_.throttle(func, [wait=0], [options={}])
Creates a throttled function that only invokes func
at most once per
-every wait
milliseconds. The throttled function comes with a cancel
-method to cancel delayed func
invocations and a flush
method to
-immediately invoke them. Provide options
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.
-
-
-If wait
is 0
and leading
is false
, func
invocation is deferred
-until to the next tick, similar to setTimeout
with a timeout of 0
.
-
-
-See David Corbacho's article
-for details over the differences between _.throttle
and _.debounce
.
0.1.0
-func
(Function): The function to throttle.[wait=0]
(number): The number of milliseconds to throttle invocations to.[options={}]
(Object): The options object.[options.leading=true]
(boolean): Specify invoking on the leading edge of the timeout.[options.trailing=true]
(boolean): Specify invoking on the trailing edge of the timeout.(Function): Returns the new throttled function.
-// Avoid excessively updating the position while scrolling.jQuery(window).on('scroll', _.throttle(updatePosition, 100)); // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.var throttled = _.throttle(renewToken, 300000, { 'trailing': false });jQuery(element).on('click', throttled); // Cancel the trailing throttled invocation.jQuery(window).on('popstate', throttled.cancel);
_.unary(func)
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(['6', '8', '10'], _.unary(parseInt));// => [6, 8, 10]
_.wrap(value, [wrapper=identity])
Creates a function that provides value
to wrapper
as its first
-argument. Any additional arguments provided to the function are appended
-to those provided to the wrapper
. The wrapper is invoked with the this
-binding of the created function.
0.1.0
-value
(*): The value to wrap.[wrapper=identity]
(Function): The wrapper function.(Function): Returns the new function.
-var p = _.wrap(_.escape, function(func, text) { return '<p>' + func(text) + '</p>';}); p('fred, barney, & pebbles');// => '<p>fred, barney, & pebbles</p>'
“Lang” Methods
_.castArray(value)
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();// => [] var array = [1, 2, 3];console.log(_.castArray(array) === array);// => true
_.clone(value)
Creates a shallow clone of value
.
-
-
-Note: This method is loosely based on the
-structured clone algorithm
-and supports cloning arrays, array buffers, booleans, date objects, maps,
-numbers, Object
objects, regexes, sets, strings, symbols, and typed
-arrays. The own enumerable properties of arguments
objects are cloned
-as plain objects. An empty object is returned for uncloneable values such
-as error objects, functions, DOM nodes, and WeakMaps.
0.1.0
-value
(*): The value to clone.(*): Returns the cloned value.
-var objects = [{ 'a': 1 }, { 'b': 2 }]; var shallow = _.clone(objects);console.log(shallow[0] === objects[0]);// => true
_.cloneDeep(value)
This 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);console.log(deep[0] === objects[0]);// => false
_.cloneDeepWith(value, [customizer])
This method is like _.cloneWith
except that it recursively clones value
.
4.0.0
-value
(*): The value to recursively clone.[customizer]
(Function): The function to customize cloning.(*): Returns the deep cloned value.
-function customizer(value) { if (_.isElement(value)) { return value.cloneNode(true); }} var el = _.cloneDeepWith(document.body, customizer); console.log(el === document.body);// => falseconsole.log(el.nodeName);// => 'BODY'console.log(el.childNodes.length);// => 20
_.cloneWith(value, [customizer])
This method is like _.clone
except that it accepts customizer
which
-is invoked to produce the cloned value. If customizer
returns undefined
,
-cloning is handled by the method instead. The customizer
is invoked with
-up to four arguments; (value [, index|key, object, stack]).
4.0.0
-value
(*): The value to clone.[customizer]
(Function): The function to customize cloning.(*): Returns the cloned value.
-function customizer(value) { if (_.isElement(value)) { return value.cloneNode(false); }} var el = _.cloneWith(document.body, customizer); console.log(el === document.body);// => falseconsole.log(el.nodeName);// => 'BODY'console.log(el.childNodes.length);// => 0
_.conformsTo(object, source)
Checks if object
conforms to source
by invoking the predicate
-properties of source
with the corresponding property values of object
.
-
-
-Note: This method is equivalent to _.conforms
when source
is
-partially applied.
4.14.0
-object
(Object): The object to inspect.source
(Object): The object of property predicates to conform to.(boolean): Returns true
if object
conforms, else false
.
var object = { 'a': 1, 'b': 2 }; _.conformsTo(object, { 'b': function(n) { return n > 1; } });// => true _.conformsTo(object, { 'b': function(n) { return n > 2; } });// => false
_.eq(value, other)
Performs 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 = { 'a': 1 };var other = { 'a': 1 }; _.eq(object, object);// => true _.eq(object, other);// => false _.eq('a', 'a');// => true _.eq('a', Object('a'));// => false _.eq(NaN, NaN);// => true
_.gt(value, other)
Checks 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);// => false
_.gte(value, other)
Checks 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);// => false
_.isArguments(value)
Checks if value
is likely an arguments
object.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is an arguments
object, else false
.
_.isArguments(function() { return arguments; }());// => true _.isArguments([1, 2, 3]);// => false
_.isArray(value)
Checks if value
is classified as an Array
object.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is an array, else false
.
_.isArray([1, 2, 3]);// => true _.isArray(document.body.children);// => false _.isArray('abc');// => false _.isArray(_.noop);// => false
_.isArrayBuffer(value)
Checks if value
is classified as an ArrayBuffer
object.
4.3.0
-value
(*): The value to check.(boolean): Returns true
if value
is an array buffer, else false
.
_.isArrayBuffer(new ArrayBuffer(2));// => true _.isArrayBuffer(new Array(2));// => false
_.isArrayLike(value)
Checks if value
is array-like. A value is considered array-like if it's
-not a function and has a value.length
that's an integer greater than or
-equal to 0
and less than or equal to Number.MAX_SAFE_INTEGER
.
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);// => false
_.isArrayLikeObject(value)
This 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);// => false
_.isBoolean(value)
Checks if value
is classified as a boolean primitive or object.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is a boolean, else false
.
_.isBoolean(false);// => true _.isBoolean(null);// => false
_.isBuffer(value)
Checks 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));// => false
_.isDate(value)
Checks if value
is classified as a Date
object.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is a date object, else false
.
_.isDate(new Date);// => true _.isDate('Mon April 23 2012');// => false
_.isElement(value)
Checks 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>');// => false
_.isEmpty(value)
Checks 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 });// => false
_.isEqual(value, other)
Performs a deep comparison between two values to determine if they are
-equivalent.
-
-
-Note: This method supports comparing arrays, array buffers, booleans,
-date objects, error objects, maps, numbers, Object
objects, regexes,
-sets, strings, symbols, and typed arrays. Object
objects are compared
-by their own, not inherited, enumerable properties. Functions and DOM
-nodes are compared by strict equality, i.e. ===
.
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 = { 'a': 1 };var other = { 'a': 1 }; _.isEqual(object, other);// => true object === other;// => false
_.isEqualWith(value, other, [customizer])
This method is like _.isEqual
except that it accepts customizer
which
-is invoked to compare values. If customizer
returns undefined
, comparisons
-are handled by the method instead. The customizer
is invoked with up to
-six arguments: (objValue, othValue [, index|key, object, other, stack]).
4.0.0
-value
(*): The value to compare.other
(*): The other value to compare.[customizer]
(Function): The function to customize comparisons.(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(array, other, customizer);// => true
_.isError(value)
Checks 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);// => false
_.isFinite(value)
Checks 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');// => false
_.isFunction(value)
Checks if value
is classified as a Function
object.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is a function, else false
.
_.isFunction(_);// => true _.isFunction(/abc/);// => false
_.isInteger(value)
Checks 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');// => false
_.isLength(value)
Checks if value
is a valid array-like length.
-
-
-Note: This method 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');// => false
_.isMap(value)
Checks if value
is classified as a Map
object.
4.3.0
-value
(*): The value to check.(boolean): Returns true
if value
is a map, else false
.
_.isMap(new Map);// => true _.isMap(new WeakMap);// => false
_.isMatch(object, source)
Performs a partial deep comparison between object
and source
to
-determine if object
contains equivalent property values.
-
-
-Note: This method is equivalent to _.matches
when source
is
-partially applied.
-
-
-Partial comparisons will match empty array and empty object source
-values against any array or object value, respectively. See _.isEqual
-for a list of supported value comparisons.
3.0.0
-object
(Object): The object to inspect.source
(Object): The object of property values to match.(boolean): Returns true
if object
is a match, else false
.
var object = { 'a': 1, 'b': 2 }; _.isMatch(object, { 'b': 2 });// => true _.isMatch(object, { 'b': 1 });// => false
_.isMatchWith(object, source, [customizer])
This method is like _.isMatch
except that it accepts customizer
which
-is invoked to compare values. If customizer
returns undefined
, comparisons
-are handled by the method instead. The customizer
is invoked with five
-arguments: (objValue, srcValue, index|key, object, source).
4.0.0
-object
(Object): The object to inspect.source
(Object): The object of property values to match.[customizer]
(Function): The function to customize comparisons.(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(object, source, customizer);// => true
_.isNaN(value)
Checks 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);// => false
_.isNative(value)
Checks 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(_);// => false
_.isNil(value)
Checks 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);// => false
_.isNull(value)
Checks 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);// => false
_.isNumber(value)
Checks if value
is classified as a Number
primitive or object.
-
-
-Note: To exclude Infinity
, -Infinity
, and NaN
, which are
-classified as numbers, use the _.isFinite
method.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is a number, else false
.
_.isNumber(3);// => true _.isNumber(Number.MIN_VALUE);// => true _.isNumber(Infinity);// => true _.isNumber('3');// => false
_.isObject(value)
Checks 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);// => false
_.isObjectLike(value)
Checks 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);// => false
_.isPlainObject(value)
Checks 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));// => true
_.isRegExp(value)
Checks if value
is classified as a RegExp
object.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is a regexp, else false
.
_.isRegExp(/abc/);// => true _.isRegExp('/abc/');// => false
_.isSafeInteger(value)
Checks if value
is a safe integer. An integer is safe if it's an IEEE-754
-double precision number which isn't the result of a rounded unsafe integer.
-
-
-Note: This method is based on
-Number.isSafeInteger
.
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');// => false
_.isSet(value)
Checks if value
is classified as a Set
object.
4.3.0
-value
(*): The value to check.(boolean): Returns true
if value
is a set, else false
.
_.isSet(new Set);// => true _.isSet(new WeakSet);// => false
_.isString(value)
Checks if value
is classified as a String
primitive or object.
0.1.0
-value
(*): The value to check.(boolean): Returns true
if value
is a string, else false
.
_.isString('abc');// => true _.isString(1);// => false
_.isSymbol(value)
Checks if value
is classified as a Symbol
primitive or object.
4.0.0
-value
(*): The value to check.(boolean): Returns true
if value
is a symbol, else false
.
_.isSymbol(Symbol.iterator);// => true _.isSymbol('abc');// => false
_.isTypedArray(value)
Checks if value
is classified as a typed array.
3.0.0
-value
(*): The value to check.(boolean): Returns true
if value
is a typed array, else false
.
_.isTypedArray(new Uint8Array);// => true _.isTypedArray([]);// => false
_.isUndefined(value)
Checks 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);// => false
_.isWeakMap(value)
Checks if value
is classified as a WeakMap
object.
4.3.0
-value
(*): The value to check.(boolean): Returns true
if value
is a weak map, else false
.
_.isWeakMap(new WeakMap);// => true _.isWeakMap(new Map);// => false
_.isWeakSet(value)
Checks if value
is classified as a WeakSet
object.
4.3.0
-value
(*): The value to check.(boolean): Returns true
if value
is a weak set, else false
.
_.isWeakSet(new WeakSet);// => true _.isWeakSet(new Set);// => false
_.lt(value, other)
Checks 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);// => false
_.lte(value, other)
Checks 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);// => false
_.toArray(value)
Converts 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);// => []
_.toFinite(value)
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.2
_.toInteger(value)
Converts 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');// => 3
_.toLength(value)
Converts 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');// => 3
_.toNumber(value)
Converts 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.2
_.toPlainObject(value)
Converts 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 }
_.toSafeInteger(value)
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');// => 3
_.toString(value)
Converts 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 convert.(string): Returns the converted string.
-_.toString(null);// => '' _.toString(-0);// => '-0' _.toString([1, 2, 3]);// => '1,2,3'
“Math” Methods
_.add(augend, addend)
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);// => 10
_.ceil(number, [precision=0])
Computes number
rounded up to precision
.
3.10.0
-number
(number): The number to round up.[precision=0]
(number): The precision to round up to.(number): Returns the rounded up number.
-_.ceil(4.006);// => 5 _.ceil(6.004, 2);// => 6.01 _.ceil(6040, -2);// => 6100
_.divide(dividend, divisor)
Divide 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.5
_.floor(number, [precision=0])
Computes number
rounded down to precision
.
3.10.0
-number
(number): The number to round down.[precision=0]
(number): The precision to round down to.(number): Returns the rounded down number.
-_.floor(4.006);// => 4 _.floor(0.046, 2);// => 0.04 _.floor(4060, -2);// => 4000
_.max(array)
Computes 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([]);// => undefined
_.maxBy(array, [iteratee=_.identity])
This method is like _.max
except that it accepts iteratee
which is
-invoked for each element in array
to generate the criterion by which
-the value is ranked. The iteratee is invoked with one argument: (value).
4.0.0
-array
(Array): The array to iterate over.[iteratee=_.identity]
(Function): The iteratee invoked per element.(*): Returns the maximum value.
-var objects = [{ 'n': 1 }, { 'n': 2 }]; _.maxBy(objects, function(o) { return o.n; });// => { 'n': 2 } // The `_.property` iteratee shorthand._.maxBy(objects, 'n');// => { 'n': 2 }
_.mean(array)
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]);// => 5
_.meanBy(array, [iteratee=_.identity])
This 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
-array
(Array): The array to iterate over.[iteratee=_.identity]
(Function): The iteratee invoked per element.(number): Returns the mean.
-var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.meanBy(objects, function(o) { return o.n; });// => 5 // The `_.property` iteratee shorthand._.meanBy(objects, 'n');// => 5
_.min(array)
Computes 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([]);// => undefined
_.minBy(array, [iteratee=_.identity])
This method is like _.min
except that it accepts iteratee
which is
-invoked for each element in array
to generate the criterion by which
-the value is ranked. The iteratee is invoked with one argument: (value).
4.0.0
-array
(Array): The array to iterate over.[iteratee=_.identity]
(Function): The iteratee invoked per element.(*): Returns the minimum value.
-var objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; });// => { 'n': 1 } // The `_.property` iteratee shorthand._.minBy(objects, 'n');// => { 'n': 1 }
_.multiply(multiplier, multiplicand)
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);// => 24
_.round(number, [precision=0])
Computes number
rounded to precision
.
3.10.0
-number
(number): The number to round.[precision=0]
(number): The precision to round to.(number): Returns the rounded number.
-_.round(4.006);// => 4 _.round(4.006, 2);// => 4.01 _.round(4060, -2);// => 4100
_.subtract(minuend, subtrahend)
Subtract 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);// => 2
_.sum(array)
Computes 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]);// => 20
_.sumBy(array, [iteratee=_.identity])
This method is like _.sum
except that it accepts iteratee
which is
-invoked for each element in array
to generate the value to be summed.
-The iteratee is invoked with one argument: (value).
4.0.0
-array
(Array): The array to iterate over.[iteratee=_.identity]
(Function): The iteratee invoked per element.(number): Returns the sum.
-var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.sumBy(objects, function(o) { return o.n; });// => 20 // The `_.property` iteratee shorthand._.sumBy(objects, 'n');// => 20
“Number” Methods
_.clamp(number, [lower], upper)
Clamps number
within the inclusive lower
and upper
bounds.
4.0.0
-number
(number): The number to clamp.[lower]
(number): The lower bound.upper
(number): The upper bound.(number): Returns the clamped number.
-_.clamp(-10, -5, 5);// => -5 _.clamp(10, -5, 5);// => 5
_.inRange(number, [start=0], end)
Checks if n
is between start
and up to, but not including, end
. If
-end
is not specified, it's set to start
with start
then set to 0
.
-If start
is greater than end
the params are swapped to support
-negative ranges.
3.3.0
-number
(number): The number to check.[start=0]
(number): The start of the range.end
(number): The end of the range.(boolean): Returns true
if number
is in the range, else false
.
_.inRange(3, 2, 4);// => true _.inRange(4, 8);// => true _.inRange(4, 2);// => false _.inRange(2, 2);// => false _.inRange(1.2, 2);// => true _.inRange(5.2, 4);// => false _.inRange(-3, -2, -6);// => true
_.random([lower=0], [upper=1], [floating])
Produces a random number between the inclusive lower
and upper
bounds.
-If only one argument is provided a number between 0
and the given number
-is returned. If floating
is true
, or either lower
or upper
are
-floats, a floating-point number is returned instead of an integer.
-
-
-Note: JavaScript follows the IEEE-754 standard for resolving
-floating-point values which can produce unexpected results.
0.7.0
-[lower=0]
(number): The lower bound.[upper=1]
(number): The upper bound.[floating]
(boolean): Specify returning a floating-point number.(number): Returns the random number.
-_.random(0, 5);// => an integer between 0 and 5 _.random(5);// => also an integer between 0 and 5 _.random(5, true);// => a floating-point number between 0 and 5 _.random(1.2, 5.2);// => a floating-point number between 1.2 and 5.2
“Object” Methods
_.assign(object, [sources])
Assigns 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.
-
-
-Note: This method mutates object
and is loosely based on
-Object.assign
.
0.10.0
-object
(Object): The destination object.[sources]
(...Object): The source objects.(Object): Returns object
.
function Foo() { this.a = 1;} function Bar() { this.c = 3;} Foo.prototype.b = 2;Bar.prototype.d = 4; _.assign({ 'a': 0 }, new Foo, new Bar);// => { 'a': 1, 'c': 3 }
_.assignIn(object, [sources])
This method is like _.assign
except that it iterates over own and
-inherited source properties.
-
-
-Note: This method mutates object
.
4.0.0
-_.extend
-object
(Object): The destination object.[sources]
(...Object): The source objects.(Object): Returns object
.
function Foo() { this.a = 1;} function Bar() { this.c = 3;} Foo.prototype.b = 2;Bar.prototype.d = 4; _.assignIn({ 'a': 0 }, new Foo, new Bar);// => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
_.assignInWith(object, sources, [customizer])
This method is like _.assignIn
except that it accepts customizer
-which is invoked to produce the assigned values. If customizer
returns
-undefined
, assignment is handled by the method instead. The customizer
-is invoked with five arguments: (objValue, srcValue, key, object, source).
-
-
-Note: This method mutates object
.
4.0.0
-_.extendWith
-object
(Object): The destination object.sources
(...Object): The source objects.[customizer]
(Function): The function to customize assigned values.(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 }
_.assignWith(object, sources, [customizer])
This method is like _.assign
except that it accepts customizer
-which is invoked to produce the assigned values. If customizer
returns
-undefined
, assignment is handled by the method instead. The customizer
-is invoked with five arguments: (objValue, srcValue, key, object, source).
-
-
-Note: This method mutates object
.
4.0.0
-object
(Object): The destination object.sources
(...Object): The source objects.[customizer]
(Function): The function to customize assigned values.(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 }
_.at(object, [paths])
Creates an array of values corresponding to paths
of object
.
1.0.0
-object
(Object): The object to iterate over.[paths]
(...(string|string[])): The property paths to pick.(Array): Returns the picked values.
-var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; _.at(object, ['a[0].b.c', 'a[1]']);// => [3, 4]
_.create(prototype, [properties])
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.[properties]
(Object): The properties to assign to the object.(Object): Returns the new object.
-function Shape() { this.x = 0; this.y = 0;} function Circle() { Shape.call(this);} Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle}); var circle = new Circle;circle instanceof Circle;// => true circle instanceof Shape;// => true
_.defaults(object, [sources])
Assigns 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.
-
-
-Note: This method mutates object
.
0.1.0
-object
(Object): The destination object.[sources]
(...Object): The source objects.(Object): Returns object
.
_.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });// => { 'a': 1, 'b': 2 }
_.defaultsDeep(object, [sources])
This method is like _.defaults
except that it recursively assigns
-default properties.
-
-
-Note: This method mutates object
.
3.10.0
-object
(Object): The destination object.[sources]
(...Object): The source objects.(Object): Returns object
.
_.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });// => { 'a': { 'b': 2, 'c': 3 } }
_.findKey(object, [predicate=_.identity])
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
-object
(Object): The object to inspect.[predicate=_.identity]
(Function): The function invoked per iteration.(*): 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(users, function(o) { return o.age < 40; });// => 'barney' (iteration order is not guaranteed) // The `_.matches` iteratee shorthand._.findKey(users, { 'age': 1, 'active': true });// => 'pebbles' // The `_.matchesProperty` iteratee shorthand._.findKey(users, ['active', false]);// => 'fred' // The `_.property` iteratee shorthand._.findKey(users, 'active');// => 'barney'
_.findLastKey(object, [predicate=_.identity])
This method is like _.findKey
except that it iterates over elements of
-a collection in the opposite order.
2.0.0
-object
(Object): The object to inspect.[predicate=_.identity]
(Function): The function invoked per iteration.(*): 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(users, function(o) { return o.age < 40; });// => returns 'pebbles' assuming `_.findKey` returns 'barney' // The `_.matches` iteratee shorthand._.findLastKey(users, { 'age': 36, 'active': true });// => 'barney' // The `_.matchesProperty` iteratee shorthand._.findLastKey(users, ['active', false]);// => 'fred' // The `_.property` iteratee shorthand._.findLastKey(users, 'active');// => 'pebbles'
_.forIn(object, [iteratee=_.identity])
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
-object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forIn(new Foo, function(value, key) { console.log(key);});// => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
_.forInRight(object, [iteratee=_.identity])
This method is like _.forIn
except that it iterates over properties of
-object
in the opposite order.
2.0.0
-object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forInRight(new Foo, function(value, key) { console.log(key);});// => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
_.forOwn(object, [iteratee=_.identity])
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
-object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forOwn(new Foo, function(value, key) { console.log(key);});// => Logs 'a' then 'b' (iteration order is not guaranteed).
_.forOwnRight(object, [iteratee=_.identity])
This method is like _.forOwn
except that it iterates over properties of
-object
in the opposite order.
2.0.0
-object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Object): Returns object
.
function Foo() { this.a = 1; this.b = 2;} Foo.prototype.c = 3; _.forOwnRight(new Foo, function(value, key) { console.log(key);});// => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
_.functions(object)
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']
_.functionsIn(object)
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']
_.get(object, path, [defaultValue])
Gets the value at path
of object
. If the resolved value is
-undefined
, the defaultValue
is returned in its place.
3.7.0
-object
(Object): The object to query.path
(Array|string): The path of the property to get.[defaultValue]
(*): The value returned for undefined
resolved values.(*): Returns the resolved value.
-var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.get(object, 'a[0].b.c');// => 3 _.get(object, ['a', '0', 'b', 'c']);// => 3 _.get(object, 'a.b.c', 'default');// => 'default'
_.has(object, path)
Checks if path
is a direct property of object
.
0.1.0
-object
(Object): The object to query.path
(Array|string): The path to check.(boolean): Returns true
if path
exists, else false
.
var object = { 'a': { 'b': 2 } };var other = _.create({ 'a': _.create({ 'b': 2 }) }); _.has(object, 'a');// => true _.has(object, 'a.b');// => true _.has(object, ['a', 'b']);// => true _.has(other, 'a');// => false
_.hasIn(object, path)
Checks if path
is a direct or inherited property of object
.
4.0.0
-object
(Object): The object to query.path
(Array|string): The path to check.(boolean): Returns true
if path
exists, else false
.
var object = _.create({ 'a': _.create({ 'b': 2 }) }); _.hasIn(object, 'a');// => true _.hasIn(object, 'a.b');// => true _.hasIn(object, ['a', 'b']);// => true _.hasIn(object, 'b');// => false
_.invert(object)
Creates an object composed of the inverted keys and values of object
.
-If object
contains duplicate values, subsequent values overwrite
-property assignments of previous values.
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' }
_.invertBy(object, [iteratee=_.identity])
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
-object
(Object): The object to invert.[iteratee=_.identity]
(Function): The iteratee invoked per element.(Object): Returns the new inverted object.
-var object = { 'a': 1, 'b': 2, 'c': 1 }; _.invertBy(object);// => { '1': ['a', 'c'], '2': ['b'] } _.invertBy(object, function(value) { return 'group' + value;});// => { 'group1': ['a', 'c'], 'group2': ['b'] }
_.invoke(object, path, [args])
Invokes the method at path
of object
.
4.0.0
-object
(Object): The object to query.path
(Array|string): The path of the method to invoke.[args]
(...*): The arguments to invoke the method with.(*): Returns the result of the invoked method.
-var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; _.invoke(object, 'a[0].b.c.slice', 1, 3);// => [2, 3]
_.keys(object)
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']
_.keysIn(object)
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)
_.mapKeys(object, [iteratee=_.identity])
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
-object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Object): Returns the new mapped object.
-_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { return key + value;});// => { 'a1': 1, 'b2': 2 }
_.mapValues(object, [iteratee=_.identity])
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
-object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.(Object): Returns the new mapped object.
-var users = { 'fred': { 'user': 'fred', 'age': 40 }, 'pebbles': { 'user': 'pebbles', 'age': 1 }}; _.mapValues(users, function(o) { return o.age; });// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) // The `_.property` iteratee shorthand._.mapValues(users, 'age');// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
_.merge(object, [sources])
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.
-
-
-Note: This method mutates object
.
0.5.0
-object
(Object): The destination object.[sources]
(...Object): The source objects.(Object): Returns object
.
var object = { 'a': [{ 'b': 2 }, { 'd': 4 }]}; var other = { 'a': [{ 'c': 3 }, { 'e': 5 }]}; _.merge(object, other);// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
_.mergeWith(object, sources, customizer)
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 six arguments:
-(objValue, srcValue, key, object, source, stack).
-
-
-Note: This method mutates object
.
4.0.0
-object
(Object): The destination object.sources
(...Object): The source objects.customizer
(Function): The function to customize assigned values.(Object): Returns object
.
function customizer(objValue, srcValue) { if (_.isArray(objValue)) { return objValue.concat(srcValue); }} var object = { 'a': [1], 'b': [2] };var other = { 'a': [3], 'b': [4] }; _.mergeWith(object, other, customizer);// => { 'a': [1, 3], 'b': [2, 4] }
_.omit(object, [paths])
The opposite of _.pick
; this method creates an object composed of the
-own and inherited enumerable property paths of object
that are not omitted.
-
-
-Note: This method is considerably slower than _.pick
.
0.1.0
-object
(Object): The source object.[paths]
(...(string|string[])): The property paths to omit.(Object): Returns the new object.
-var object = { 'a': 1, 'b': '2', 'c': 3 }; _.omit(object, ['a', 'c']);// => { 'b': '2' }
_.omitBy(object, [predicate=_.identity])
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
-object
(Object): The source object.[predicate=_.identity]
(Function): The function invoked per property.(Object): Returns the new object.
-var object = { 'a': 1, 'b': '2', 'c': 3 }; _.omitBy(object, _.isNumber);// => { 'b': '2' }
_.pick(object, [paths])
Creates an object composed of the picked object
properties.
0.1.0
-object
(Object): The source object.[paths]
(...(string|string[])): The property paths to pick.(Object): Returns the new object.
-var object = { 'a': 1, 'b': '2', 'c': 3 }; _.pick(object, ['a', 'c']);// => { 'a': 1, 'c': 3 }
_.pickBy(object, [predicate=_.identity])
Creates an object composed of the object
properties predicate
returns
-truthy for. The predicate is invoked with two arguments: (value, key).
4.0.0
-object
(Object): The source object.[predicate=_.identity]
(Function): The function invoked per property.(Object): Returns the new object.
-var object = { 'a': 1, 'b': '2', 'c': 3 }; _.pickBy(object, _.isNumber);// => { 'a': 1, 'c': 3 }
_.result(object, path, [defaultValue])
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
-object
(Object): The object to query.path
(Array|string): The path of the property to resolve.[defaultValue]
(*): The value returned for undefined
resolved values.(*): Returns the resolved value.
-var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; _.result(object, 'a[0].b.c1');// => 3 _.result(object, 'a[0].b.c2');// => 4 _.result(object, 'a[0].b.c3', 'default');// => 'default' _.result(object, 'a[0].b.c3', _.constant('default'));// => 'default'
_.set(object, path, value)
Sets the value at path
of object
. If a portion of path
doesn't exist,
-it's created. Arrays are created for missing index properties while objects
-are created for all other missing properties. Use _.setWith
to customize
-path
creation.
-
-
-Note: This method mutates object
.
3.7.0
-object
(Object): The object to modify.path
(Array|string): The path of the property to set.value
(*): The value to set.(Object): Returns object
.
var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.set(object, 'a[0].b.c', 4);console.log(object.a[0].b.c);// => 4 _.set(object, ['x', '0', 'y', 'z'], 5);console.log(object.x[0].y.z);// => 5
_.setWith(object, path, value, [customizer])
This method is like _.set
except that it accepts customizer
which is
-invoked to produce the objects of path
. If customizer
returns undefined
-path creation is handled by the method instead. The customizer
is invoked
-with three arguments: (nsValue, key, nsObject).
-
-
-Note: This method mutates object
.
4.0.0
-object
(Object): The object to modify.path
(Array|string): The path of the property to set.value
(*): The value to set.[customizer]
(Function): The function to customize assigned values.(Object): Returns object
.
var object = {}; _.setWith(object, '[0][1]', 'a', Object);// => { '0': { '1': 'a' } }
_.toPairs(object)
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)
_.toPairsIn(object)
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)
_.transform(object, [iteratee=_.identity], [accumulator])
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
-object
(Object): The object to iterate over.[iteratee=_.identity]
(Function): The function invoked per iteration.[accumulator]
(*): The custom accumulator value.(*): Returns the accumulated value.
-_.transform([2, 3, 4], function(result, n) { result.push(n *= n); return n % 2 == 0;}, []);// => [4, 9] _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { (result[value] || (result[value] = [])).push(key);}, {});// => { '1': ['a', 'c'], '2': ['b'] }
_.unset(object, path)
Removes the property at path
of object
.
-
-
-Note: This method mutates object
.
4.0.0
-object
(Object): The object to modify.path
(Array|string): The path of the property to unset.(boolean): Returns true
if the property is deleted, else false
.
var object = { 'a': [{ 'b': { 'c': 7 } }] };_.unset(object, 'a[0].b.c');// => true console.log(object);// => { 'a': [{ 'b': {} }] }; _.unset(object, ['a', '0', 'b', 'c']);// => true console.log(object);// => { 'a': [{ 'b': {} }] };
_.update(object, path, updater)
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).
-
-
-Note: This method mutates object
.
4.6.0
-object
(Object): The object to modify.path
(Array|string): The path of the property to set.updater
(Function): The function to produce the updated value.(Object): Returns object
.
var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.update(object, 'a[0].b.c', function(n) { return n * n; });console.log(object.a[0].b.c);// => 9 _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });console.log(object.x[0].y.z);// => 0
_.updateWith(object, path, updater, [customizer])
This 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).
-
-
-Note: This method mutates object
.
4.6.0
-object
(Object): The object to modify.path
(Array|string): The path of the property to set.updater
(Function): The function to produce the updated value.[customizer]
(Function): The function to customize assigned values.(Object): Returns object
.
var object = {}; _.updateWith(object, '[0][1]', _.constant('a'), Object);// => { '0': { '1': 'a' } }
_.values(object)
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']
_.valuesIn(object)
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)
“Seq” Methods
_(value)
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 and 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
, conformsTo
, deburr
,
-defaultTo
, 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
value
(*): The value to wrap in a lodash
instance.(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());// => true
_.chain(value)
Creates 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'
_.tap(value, interceptor)
This method invokes interceptor
and returns value
. The interceptor
-is invoked with one argument; (value). The purpose of this method is to
-"tap into" a method chain sequence in order to modify intermediate results.
0.1.0
-value
(*): The value to provide to interceptor
.interceptor
(Function): The function to invoke.(*): Returns value
.
_([1, 2, 3]) .tap(function(array) {// Mutate input array. array.pop(); }) .reverse() .value();// => [2, 1]
_.thru(value, interceptor)
This method is like _.tap
except that it returns the result of interceptor
.
-The purpose of this method is to "pass thru" values replacing intermediate
-results in a method chain sequence.
3.0.0
-value
(*): The value to provide to interceptor
.interceptor
(Function): The function to invoke.(*): Returns the result of interceptor
.
_(' abc ') .chain() .trim() .thru(function(value) { return [value]; }) .value();// => ['abc']
_.prototype[Symbol.iterator]()
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]
_.prototype.at([paths])
This method is the wrapper version of _.at
.
1.0.0
-[paths]
(...(string|string[])): The property paths to pick.(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]
_.prototype.chain()
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' }
_.prototype.commit()
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); console.log(array);// => [1, 2] wrapped = wrapped.commit();console.log(array);// => [1, 2, 3] wrapped.last();// => 3 console.log(array);// => [1, 2, 3]
_.prototype.next()
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 }
_.prototype.plant(value)
Creates a clone of the chain sequence planting value
as the wrapped value.
3.2.0
-value
(*): The value to plant.(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]
_.prototype.reverse()
This method is the wrapper version of _.reverse
.
-
-
-Note: This method mutates the wrapped array.
0.1.0
-(Object): Returns the new lodash
wrapper instance.
var array = [1, 2, 3]; _(array).reverse().value()// => [3, 2, 1] console.log(array);// => [3, 2, 1]
“String” Methods
_.camelCase([string=''])
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'
_.capitalize([string=''])
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'
_.deburr([string=''])
Deburrs string
by converting
-Latin-1 Supplement
-and Latin Extended-A
-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'
_.endsWith([string=''], [target], [position=string.length])
Checks if string
ends with the given target string.
3.0.0
-[string='']
(string): The string to inspect.[target]
(string): The string to search for.[position=string.length]
(number): The position to search up to.(boolean): Returns true
if string
ends with target
, else false
.
_.endsWith('abc', 'c');// => true _.endsWith('abc', 'b');// => false _.endsWith('abc', 'b', 2);// => true
_.escape([string=''])
Converts the characters "&", "<", ">", '"', and "'" in string
to their
-corresponding HTML entities.
-
-
-Note: No other characters are escaped. To escape additional
-characters use a third-party library like he.
-
-
-Though the ">" character is escaped for symmetry, characters like
-">" and "/" don't need escaping in HTML and have no special meaning
-unless they're part of a tag or unquoted attribute value. See
-Mathias Bynens's article
-(under "semi-related fun fact") for more details.
-
-
-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'
_.escapeRegExp([string=''])
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/\)'
_.kebabCase([string=''])
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'
_.lowerCase([string=''])
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'
_.lowerFirst([string=''])
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'
_.pad([string=''], [length=0], [chars=' '])
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
-[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
-_.pad('abc', 8);// => ' abc ' _.pad('abc', 8, '_-');// => '_-abc_-_' _.pad('abc', 3);// => 'abc'
_.padEnd([string=''], [length=0], [chars=' '])
Pads string
on the right side if it's shorter than length
. Padding
-characters are truncated if they exceed length
.
4.0.0
-[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
-_.padEnd('abc', 6);// => 'abc ' _.padEnd('abc', 6, '_-');// => 'abc_-_' _.padEnd('abc', 3);// => 'abc'
_.padStart([string=''], [length=0], [chars=' '])
Pads string
on the left side if it's shorter than length
. Padding
-characters are truncated if they exceed length
.
4.0.0
-[string='']
(string): The string to pad.[length=0]
(number): The padding length.[chars=' ']
(string): The string used as padding.(string): Returns the padded string.
-_.padStart('abc', 6);// => ' abc' _.padStart('abc', 6, '_-');// => '_-_abc' _.padStart('abc', 3);// => 'abc'
_.parseInt(string, [radix=10])
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
-string
(string): The string to convert.[radix=10]
(number): The radix to interpret value
by.(number): Returns the converted integer.
-_.parseInt('08');// => 8 _.map(['6', '08', '10'], _.parseInt);// => [6, 8, 10]
_.repeat([string=''], [n=1])
Repeats the given string n
times.
3.0.0
-[string='']
(string): The string to repeat.[n=1]
(number): The number of times to repeat the string.(string): Returns the repeated string.
-_.repeat('*', 3);// => '***' _.repeat('abc', 2);// => 'abcabc' _.repeat('abc', 0);// => ''
_.replace([string=''], pattern, replacement)
Replaces matches for pattern
in string
with replacement
.
-
-
-Note: This method is based on
-String#replace
.
4.0.0
-[string='']
(string): The string to modify.pattern
(RegExp|string): The pattern to replace.replacement
(Function|string): The match replacement.(string): Returns the modified string.
-_.replace('Hi Fred', 'Fred', 'Barney');// => 'Hi Barney'
_.snakeCase([string=''])
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'
_.split([string=''], separator, [limit])
Splits string
by separator
.
-
-
-Note: This method is based on
-String#split
.
4.0.0
-[string='']
(string): The string to split.separator
(RegExp|string): The separator pattern to split by.[limit]
(number): The length to truncate results to.(Array): Returns the string segments.
-_.split('a-b-c', '-', 2);// => ['a', 'b']
_.startCase([string=''])
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'
_.startsWith([string=''], [target], [position=0])
Checks if string
starts with the given target string.
3.0.0
-[string='']
(string): The string to inspect.[target]
(string): The string to search for.[position=0]
(number): The position to search from.(boolean): Returns true
if string
starts with target
, else false
.
_.startsWith('abc', 'a');// => true _.startsWith('abc', 'b');// => false _.startsWith('abc', 'b', 1);// => true
_.template([string=''], [options={}])
Creates a compiled template function that can interpolate data properties
-in "interpolate" delimiters, HTML-escape interpolated data properties in
-"escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
-properties may be accessed as free variables in the template. If a setting
-object is given, it takes precedence over _.templateSettings
values.
-
-
-Note: In the development build _.template
utilizes
-sourceURLs
-for easier debugging.
-
-
-For more information on precompiling templates see
-lodash's custom builds documentation.
-
-
-For more information on Chrome extension sandboxes see
-Chrome's extensions documentation.
0.1.0
-[string='']
(string): The template string.[options={}]
(Object): The options object.[options.escape=_.templateSettings.escape]
(RegExp): The HTML "escape" delimiter.[options.evaluate=_.templateSettings.evaluate]
(RegExp): The "evaluate" delimiter.[options.imports=_.templateSettings.imports]
(Object): An object to import into the template as free variables.[options.interpolate=_.templateSettings.interpolate]
(RegExp): The "interpolate" delimiter.[options.sourceURL='lodash.templateSources[n]']
(string): The sourceURL of the compiled template.[options.variable='obj']
(string): The data object variable name.(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 template literal delimiter as an "interpolate" delimiter.// Disable support by replacing the "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 + '\ };\');
_.toLower([string=''])
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__'
_.toUpper([string=''])
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__'
_.trim([string=''], [chars=whitespace])
Removes leading and trailing whitespace or specified characters from string
.
3.0.0
-[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
-_.trim(' abc ');// => 'abc' _.trim('-_-abc-_-', '_-');// => 'abc' _.map([' foo ', ' bar '], _.trim);// => ['foo', 'bar']
_.trimEnd([string=''], [chars=whitespace])
Removes trailing whitespace or specified characters from string
.
4.0.0
-[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
-_.trimEnd(' abc ');// => ' abc' _.trimEnd('-_-abc-_-', '_-');// => '-_-abc'
_.trimStart([string=''], [chars=whitespace])
Removes leading whitespace or specified characters from string
.
4.0.0
-[string='']
(string): The string to trim.[chars=whitespace]
(string): The characters to trim.(string): Returns the trimmed string.
-_.trimStart(' abc ');// => 'abc ' _.trimStart('-_-abc-_-', '_-');// => 'abc-_-'
_.truncate([string=''], [options={}])
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
-[string='']
(string): The string to truncate.[options={}]
(Object): The options object.[options.length=30]
(number): The maximum string length.[options.omission='...']
(string): The string to indicate text is omitted.[options.separator]
(RegExp|string): The separator pattern to truncate to.(string): Returns the truncated string.
-_.truncate('hi-diddly-ho there, neighborino');// => 'hi-diddly-ho there, neighbo...' _.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' '});// => 'hi-diddly-ho there,...' _.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/});// => 'hi-diddly-ho there...' _.truncate('hi-diddly-ho there, neighborino', { 'omission': ' [...]'});// => 'hi-diddly-ho there, neig [...]'
_.unescape([string=''])
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'
_.upperCase([string=''])
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'
_.upperFirst([string=''])
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'
_.words([string=''], [pattern])
Splits string
into an array of its words.
3.0.0
-[string='']
(string): The string to inspect.[pattern]
(RegExp|string): The pattern to match words.(Array): Returns the words of string
.
_.words('fred, barney, & pebbles');// => ['fred', 'barney', 'pebbles'] _.words('fred, barney, & pebbles', /[^, ]+/g);// => ['fred', 'barney', '&', 'pebbles']
“Util” Methods
_.attempt(func, [args])
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.[args]
(...*): The arguments to invoke func
with.(*): 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 = [];}
_.bindAll(object, methodNames)
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
-object
(Object): The object to bind and assign the bound methods to.methodNames
(...(string|string[])): The object method names to bind.(Object): Returns object
.
var view = { 'label': 'docs', 'click': function() { console.log('clicked ' + this.label); }}; _.bindAll(view, ['click']);jQuery(element).on('click', view.click);// => Logs 'clicked docs' when clicked.
_.cond(pairs)
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')], [_.stubTrue, _.constant('no match')]]); func({ 'a': 1, 'b': 2 });// => 'matches A' func({ 'a': 0, 'b': 1 });// => 'matches B' func({ 'a': '1', 'b': '2' });// => 'no match'
_.conforms(source)
Creates a function that invokes the predicate properties of source
with
-the corresponding property values of a given object, returning true
if
-all predicates return truthy, else false
.
-
-
-Note: The created function is equivalent to _.conformsTo
with
-source
partially applied.
4.0.0
-source
(Object): The object of property predicates to conform to.(Function): Returns the new spec function.
-var objects = [ { 'a': 2, 'b': 1 }, { 'a': 1, 'b': 2 }]; _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));// => [{ 'a': 1, 'b': 2 }]
_.constant(value)
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(2, _.constant({ 'a': 1 })); console.log(objects);// => [{ 'a': 1 }, { 'a': 1 }] console.log(objects[0] === objects[1]);// => true
_.defaultTo(value, defaultValue)
Checks value
to determine whether a default value should be returned in
-its place. The defaultValue
is returned if value
is NaN
, null
,
-or undefined
.
4.14.0
-value
(*): The value to check.defaultValue
(*): The default value.(*): Returns the resolved value.
-_.defaultTo(1, 10);// => 1 _.defaultTo(undefined, 10);// => 10
_.flow([funcs])
Creates a function that returns the result of invoking the given functions
-with the this
binding of the created function, where each successive
-invocation is supplied the return value of the previous.
3.0.0
-[funcs]
(...(Function|Function[])): The functions to invoke.(Function): Returns the new composite function.
-function square(n) { return n * n;} var addSquare = _.flow([_.add, square]);addSquare(1, 2);// => 9
_.flowRight([funcs])
This 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[])): The functions to invoke.(Function): Returns the new composite function.
-function square(n) { return n * n;} var addSquare = _.flowRight([square, _.add]);addSquare(1, 2);// => 9
_.identity(value)
This method returns the first argument it receives.
-0.1.0
-value
(*): Any value.(*): Returns value
.
var object = { 'a': 1 }; console.log(_.identity(object) === object);// => true
_.iteratee([func=_.identity])
Creates 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=_.identity]
(*): 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(users, _.iteratee({ 'user': 'barney', 'active': true }));// => [{ 'user': 'barney', 'age': 36, 'active': true }] // The `_.matchesProperty` iteratee shorthand._.filter(users, _.iteratee(['user', 'fred']));// => [{ 'user': 'fred', 'age': 40 }] // The `_.property` iteratee shorthand._.map(users, _.iteratee('user'));// => ['barney', 'fred'] // Create custom iteratee shorthands._.iteratee = _.wrap(_.iteratee, function(iteratee, func) { return !_.isRegExp(func) ? iteratee(func) : function(string) { return func.test(string); };}); _.filter(['abc', 'def'], /ef/);// => ['def']
_.matches(source)
Creates a function that performs a partial deep comparison between a given
-object and source
, returning true
if the given object has equivalent
-property values, else false
.
-
-
-Note: The created function is equivalent to _.isMatch
with source
-partially applied.
-
-
-Partial comparisons will match empty array and empty object source
-values against any array or object value, respectively. See _.isEqual
-for a list of supported value comparisons.
3.0.0
-source
(Object): The object of property values to match.(Function): Returns the new spec function.
-var objects = [ { 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]; _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));// => [{ 'a': 4, 'b': 5, 'c': 6 }]
_.matchesProperty(path, srcValue)
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: Partial comparisons will match empty array and empty object
-srcValue
values against any array or object value, respectively. See
-_.isEqual
for a list of supported value comparisons.
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 objects = [ { 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]; _.find(objects, _.matchesProperty('a', 4));// => { 'a': 4, 'b': 5, 'c': 6 }
_.method(path, [args])
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.[args]
(...*): The arguments to invoke the method with.(Function): Returns the new invoker function.
-var objects = [ { 'a': { 'b': _.constant(2) } }, { 'a': { 'b': _.constant(1) } }]; _.map(objects, _.method('a.b'));// => [2, 1] _.map(objects, _.method(['a', 'b']));// => [2, 1]
_.methodOf(object, [args])
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.[args]
(...*): The arguments to invoke the method with.(Function): Returns the new invoker function.
-var array = _.times(3, _.constant), object = { 'a': array, 'b': array, 'c': array }; _.map(['a[2]', 'c[0]'], _.methodOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.methodOf(object));// => [2, 0]
_.mixin([object=lodash], source, [options={}])
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=lodash]
(Function|Object): The destination object.source
(Object): The object of functions to add.[options={}]
(Object): The options object.[options.chain=true]
(boolean): Specify whether mixins are chainable.(*): Returns object
.
function vowels(string) { return _.filter(string, function(v) { return /[aeiou]/i.test(v); });} _.mixin({ 'vowels': vowels });_.vowels('fred');// => ['e'] _('fred').vowels().value();// => ['e'] _.mixin({ 'vowels': vowels }, { 'chain': false });_('fred').vowels();// => ['e']
_.noConflict()
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();
_.noop()
This method returns undefined
.
2.3.0
-_.times(2, _.noop);// => [undefined, undefined]
_.nthArg([n=0])
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=0]
(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'
_.over([iteratees=[_.identity]])
Creates a function that invokes iteratees
with the arguments it receives
-and returns their results.
4.0.0
-[iteratees=[_.identity]]
(...(Function|Function[])): The iteratees to invoke.(Function): Returns the new function.
-var func = _.over([Math.max, Math.min]); func(1, 2, 3, 4);// => [4, 1]
_.overEvery([predicates=[_.identity]])
Creates a function that checks if all of the predicates
return
-truthy when invoked with the arguments it receives.
4.0.0
-[predicates=[_.identity]]
(...(Function|Function[])): The predicates to check.(Function): Returns the new function.
-var func = _.overEvery([Boolean, isFinite]); func('1');// => true func(null);// => false func(NaN);// => false
_.overSome([predicates=[_.identity]])
Creates a function that checks if any of the predicates
return
-truthy when invoked with the arguments it receives.
4.0.0
-[predicates=[_.identity]]
(...(Function|Function[])): The predicates to check.(Function): Returns the new function.
-var func = _.overSome([Boolean, isFinite]); func('1');// => true func(null);// => true func(NaN);// => false
_.property(path)
Creates 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(objects, _.property('a.b'));// => [2, 1] _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');// => [1, 2]
_.propertyOf(object)
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(['a[2]', 'c[0]'], _.propertyOf(object));// => [2, 0] _.map([['a', '2'], ['c', '0']], _.propertyOf(object));// => [2, 0]
_.range([start=0], end, [step=1])
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=0]
(number): The start of the range.end
(number): The end of the range.[step=1]
(number): The value to increment or decrement by.(Array): Returns the range of numbers.
-_.range(4);// => [0, 1, 2, 3] _.range(-4);// => [0, -1, -2, -3] _.range(1, 5);// => [1, 2, 3, 4] _.range(0, 20, 5);// => [0, 5, 10, 15] _.range(0, -4, -1);// => [0, -1, -2, -3] _.range(1, 4, 0);// => [1, 1, 1] _.range(0);// => []
_.rangeRight([start=0], end, [step=1])
This method is like _.range
except that it populates values in
-descending order.
4.0.0
-[start=0]
(number): The start of the range.end
(number): The end of the range.[step=1]
(number): The value to increment or decrement by.(Array): Returns the range of numbers.
-_.rangeRight(4);// => [3, 2, 1, 0] _.rangeRight(-4);// => [-3, -2, -1, 0] _.rangeRight(1, 5);// => [4, 3, 2, 1] _.rangeRight(0, 20, 5);// => [15, 10, 5, 0] _.rangeRight(0, -4, -1);// => [-3, -2, -1, 0] _.rangeRight(1, 4, 0);// => [1, 1, 1] _.rangeRight(0);// => []
_.runInContext([context=root])
Create a new pristine lodash
function using the context
object.
1.1.0
-[context=root]
(Object): The context object.(Function): Returns a new lodash
function.
_.mixin({ 'foo': _.constant('foo') }); var lodash = _.runInContext();lodash.mixin({ 'bar': lodash.constant('bar') }); _.isFunction(_.foo);// => true_.isFunction(_.bar);// => false lodash.isFunction(lodash.foo);// => falselodash.isFunction(lodash.bar);// => true // Create a suped-up `defer` in Node.js.var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
_.stubArray()
This method returns a new empty array.
-4.13.0
-(Array): Returns the new empty array.
-var arrays = _.times(2, _.stubArray); console.log(arrays);// => [[], []] console.log(arrays[0] === arrays[1]);// => false
_.stubFalse()
This method returns false
.
4.13.0
-(boolean): Returns false
.
_.times(2, _.stubFalse);// => [false, false]
_.stubObject()
This method returns a new empty object.
-4.13.0
-(Object): Returns the new empty object.
-var objects = _.times(2, _.stubObject); console.log(objects);// => [{}, {}] console.log(objects[0] === objects[1]);// => false
_.stubString()
This method returns an empty string.
-4.13.0
-(string): Returns the empty string.
-_.times(2, _.stubString);// => ['', '']
_.stubTrue()
This method returns true
.
4.13.0
-(boolean): Returns true
.
_.times(2, _.stubTrue);// => [true, true]
_.times(n, [iteratee=_.identity])
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
-n
(number): The number of times to invoke iteratee
.[iteratee=_.identity]
(Function): The function invoked per iteration.(Array): Returns the array of results.
-_.times(3, String);// => ['0', '1', '2'] _.times(4, _.constant(0));// => [0, 0, 0, 0]
_.toPath(value)
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']
_.uniqueId([prefix=''])
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'
Properties
_.templateSettings
(Object): By default, the template delimiters used by lodash are like those in -embedded Ruby (ERB) as well as ES2015 template strings. Change the -following template settings to use alternative delimiters.
- -Methods
_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });// → { 'a': 1, 'b': 2 }_.partition([1, 2, 3, 4], n => n % 2);// → [[1, 3], [2, 4]]
Lodash is released under the MIT license & supports modern environments. Review the build differences & pick one thatβs right for you.
-In a browser:
- {% raw %} -<script src="lodash.js"></script>
Using npm:
- {% raw %} -$ npm i -g npm$ npm i --save lodash
In Node.js:
- {% raw %} -// Load the full build.var _ = require('lodash');// Load the core build.var _ = require('lodash/core');// Load the FP build for immutable auto-curried iteratee-first data-last methods.var fp = require('lodash/fp'); // Load method categories.var array = require('lodash/array');var object = require('lodash/fp/object'); // Cherry-pick methods for smaller browserify/rollup/webpack bundles.var at = require('lodash/at');var curryN = require('lodash/fp/curryN');
Note:
Install n_ for Lodash use in the Node.js < 6 REPL.
Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. Lodashβs modular methods are great for:
-Lodash is available in a variety of builds & module formats.
- -Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.
-
- Lodash methods are available in standalone per method packages
- like lodash.mapvalues
, lodash.pickby
, etc.
- These packages contain only the code the method depends on.
-
- - However, use of these packages is discouraged and they will be removed in v5. - -
-
- Although they may seem more lightweight, they will usually increase the size of
- node_modules
and webpack/rollup bundles in a project that
- transitively depends on multiple per method packages and/or the main
- lodash
package. Whereas many methods in the main
- lodash
package share code, the per method packages internally
- bundle copies of any code they depend on.
-
- For example, throttle
uses debounce
internally.
- In a project using both methods from the main lodash
package,
- throttle
will import the same debounce
module as
- any code that imports debounce
directly, so only one copy of
- debounce
will wind up in a webpack bundle.
-
- On the other hand, if a project imports throttle
from
- lodash.throttle
, the extra copy of the debounce
- code internally bundled into lodash.throttle
will wind
- up in the webpack bundle, in addition to debounce
from the main
- lodash
package or lodash.debounce
.
-
lodash
isn't lightweight enough!
- Don't worry—if you import or require methods
- directly, e.g. const throttle = require('lodash/throttle')
, only
- the subset of lodash code your package uses will be bundled
- in projects that use your package.
-
- If importing this way seems cumbersome, you can use
- babel-plugin-lodash
- to transform named top-level imports like
- import { throttle, debounce } from 'lodash'
into direct import statements.
-
- Furthermore, modern tree-shaking bundlers like webpack and rollup can avoid - bundling code you don't need even if you don't use direct imports or the babel plugin. -
-lodash
package
- A jscodeshift transform is available to convert per method package imports
- to main lodash
package imports.
-
-
-
+ Site made with β€οΈ by
+ Maintained by the
{`
+$ npm i lodash
+# or
+yarn add lodash
+`}
+
+ {`
+// Load the full build.
+const _ = require('lodash');
+// Load the core build.
+const _ = require('lodash/core');
+// Load the FP build for immutable auto-curried iteratee-first data-last methods.
+const fp = require('lodash/fp');
+
+// Load method categories.
+const array = require('lodash/array');
+const object = require('lodash/fp/object');
+
+// Cherry-pick methods for smaller browserify/rollup/webpack bundles.
+const at = require('lodash/at');
+const curryN = require('lodash/fp/curryN');
+`}
+
+ You just hit a route that doesn't exist... the sadness.
++ Lodash makes JavaScript easier by taking the hassle out of working with + arrays, numbers, objects, strings, etc. Lodashβs modular methods are + great for: +
+ +
+ Review the
Lodash is available in a variety of builds & module formats.
+ +
+ Install
+ Tested in Chrome 54-55, Firefox 49-50, IE 11, Edge 14, Safari 9-10, + Node.js 6-7, & PhantomJS 2.1.1. Automated browser & CI test runs are + available. +
+