",")","https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js","https://cdn.jsdelivr.net/npm/[email protected]/underscore-esm-min.js","https://unpkg.com/[email protected]/underscore-umd-min.js","https://unpkg.com/[email protected]/underscore-esm-min.js","https://pagecdn.io/lib/underscore/1.13.7/underscore-umd-min.js","https://pagecdn.io/lib/underscore/1.13.7/underscore-esm-min.js","https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.7/underscore-umd-min.js","https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.7/underscore-esm-min.js","In most cases, you can replace the version number above by\n ","latest"," so that your embed will automatically use the latest\n version, or ","stable"," if you want to delay updating until an update\n has proven to be free of accidental breaking changes. Example:","https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js","Package Installation","Node.js","npm install underscore","Meteor.js","meteor add underscore","Bower","bower install underscore","If you are hardcoding the path to the file within the package and you\n are unsure which build to use, it is very likely that you need\n ","underscore-umd.js"," or the minified variant\n ","underscore-umd-min.js",".","Monolithic Import (recommended)","ESM","import _, { map } from 'underscore';","AMD","require(['underscore'], ...)","CommonJS","var _ = require('underscore');","ExtendScript","#include \"underscore-umd.js\"","Modular Import","import map from 'underscore/modules/map.js'","require(['underscore/amd/map.js'], ...)","var map = require('underscore/cjs/map.js');","For functions with multiple aliases, the file name of the module is\n always the ","first"," name that appears in the documentation. For\n example, ","_.reduce","/","_.inject","_.foldl"," is exported\n from ","underscore/modules/reduce.js",". Modular usage is mostly\n recommended for creating a customized build of Underscore.","Engine Compatibility","\n Underscore 1.x is backwards compatible with any engine that fully\n supports ES3, while also utilizing newer features when available, such as\n ","Object.keys",", typed arrays and ES modules. We routinely run our\n unittests against the JavaScript engines listed below:\n ","Chrome 26–latest","Edge 13, 18 and latest","Firefox 11–latest","Internet Explorer 9–11","Node.js 8–latest LTS","Safari 8–latest","\n In addition:\n ","\n We have recent confirmation that the library is compatible with Adobe\n ExtendScript.\n ","\n There is support code present for IE 8, which we will retain in\n future Underscore 1.x updates.\n ","\n Patches to enhance support for other ES3-compatible environments\n are always welcome.\n ","\n Underscore 2.x will likely remove support for some outdated environments.\n ","Collection Functions (Arrays or Objects)","each","_.each(list, iteratee, [context])","Alias: forEach","source","\n Iterates over a ","list"," of elements, yielding each in turn to an\n ","iteratee"," function.\n The "," is bound to the ","context"," object, if one is\n passed. Each invocation of "," is called with three arguments:\n ","(element, index, list)",". If "," is a JavaScript object, ","'s\n arguments will be ","(value, key, list)",". Returns the "," for chaining.\n ","\n_.each([1, 2, 3], alert);\n=> alerts each number in turn...\n_.each({one: 1, two: 2, three: 3}, alert);\n=> alerts each number value in turn...","\n Note: Collection functions work on arrays, objects, and\n array-like objects such as","arguments",", ","NodeList","\n and similar. But it works by duck-typing, so avoid passing objects with\n a numeric ","length"," property. It's also good to note that an\n "," loop cannot be broken out of — to break, use ","_.find","\n instead.\n ","map","_.map(list, iteratee, [context])","Alias: collect","\n Produces a new array of values by mapping each value in ","\n through a transformation function (",").\n The iteratee is passed three arguments: the ","value",",\n then the ","index"," (or ","key",") of the iteration,\n and finally a reference to the entire ",".\n ","\n_.map([1, 2, 3], function(num){ return num * 3; });\n=> [3, 6, 9]\n_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });\n=> [3, 6, 9]\n_.map([[1, 2], [3, 4]], _.first);\n=> [1, 3]","reduce","_.reduce(list, iteratee, [memo], [context])","Aliases: inject, foldl","\n Also known as ","inject"," and ","foldl",", reduce boils down a "," of values into a single value.\n ","Memo"," is the initial state of the reduction, and each successive step of it should be returned by\n ",". The iteratee is passed four arguments: the ","memo",", then the "," and\n "," (or key) of the iteration, and finally a reference to the entire ","\n If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element\n of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next\n element in the list.\n ","\nvar sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);\n=> 6\n","reduceRight","_.reduceRight(list, iteratee, [memo], [context])","Alias: foldr","\n The right-associative version of ",". ","Foldr","\n is not as useful in JavaScript as it would be in a language with lazy\n evaluation.\n ","\nvar list = [[0, 1], [2, 3], [4, 5]];\nvar flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);\n=> [4, 5, 2, 3, 0, 1]\n","find","_.find(list, predicate, [context])","Alias: detect","\n Looks through each value in the ",", returning the first one that\n passes a truth test (","predicate","), or ","undefined"," if no value\n passes the test. The function returns as\n soon as it finds an acceptable element, and doesn't traverse the\n entire list.\n "," is transformed through ","\n to facilitate shorthand syntaxes.\n ","\nvar even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n=> 2\n","filter","_.filter(list, predicate, [context])","Alias: select",", returning an array of all\n the values that pass a truth test (",").\n ","\nvar evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n=> [2, 4, 6]\n","findWhere","_.findWhere(list, properties)","\n Looks through the "," and returns the "," value that ","matches","\n all of the key-value pairs listed in ","properties","\n If no match is found, or if list is empty, undefined will be\n returned.\n ","\n_.findWhere(publicServicePulitzers, {newsroom: \"The New York Times\"});\n=> {year: 1918, newsroom: \"The New York Times\",\n reason: \"For its public service in publishing in full so many official reports,\n documents and speeches by European statesmen relating to the progress and\n conduct of the war.\"}\n","where","_.where(list, properties)",", returning an array of all\n the values that "," the key-value pairs listed in ","\n_.where(listOfPlays, {author: \"Shakespeare\", year: 1611});\n=> [{title: \"Cymbeline\", author: \"Shakespeare\", year: 1611},\n {title: \"The Tempest\", author: \"Shakespeare\", year: 1611}]\n","reject","_.reject(list, predicate, [context])","\n Returns the values in "," without the elements that the truth\n test (",") passes. The opposite of ",".\n ","\nvar odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n=> [1, 3, 5]\n","every","_.every(list, [predicate], [context])","Alias: all","\n Returns ","true"," if all of the values in the "," pass the\n "," truth test. Short-circuits and stops traversing the list\n if a false element is found.\n ","\n_.every([2, 4, 5], function(num) { return num % 2 == 0; });\n=> false\n","some","_.some(list, [predicate], [context])","Alias: any"," if any of the values in the "," truth test. Short-circuits and stops traversing the list\n if a true element is found.\n ","\n_.some([null, 0, 'yes', false]);\n=> true\n","contains","_.contains(list, value, [fromIndex])","Aliases: include, includes"," if the "," is present in the ",".\n Uses ","indexOf"," internally, if "," is an Array.\n Use ","fromIndex"," to start your search at a given index.\n ","\n_.contains([1, 2, 3], 3);\n=> true\n","invoke","_.invoke(list, methodName, *arguments)","\n Calls the method named by ","methodName"," on each value in the ",".\n Any extra arguments passed to "," will be forwarded on to the\n method invocation.\n ","\n_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');\n=> [[1, 5, 7], [1, 2, 3]]\n","pluck","_.pluck(list, propertyName)","\n A convenient version of what is perhaps the most common use-case for\n ",": extracting a list of property values.\n ","\nvar stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];\n_.pluck(stooges, 'name');\n=> [\"moe\", \"larry\", \"curly\"]\n","max","_.max(list, [iteratee], [context])","\n Returns the maximum value in ",". If an ","\n function is provided, it will be used on each value to generate the\n criterion by which the value is ranked. ","-Infinity"," is returned\n if "," is empty, so an ","isEmpty"," guard\n may be required. This function can currently only compare numbers reliably.\n This function uses operator ","<","\n (","note",").\n ","\nvar stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];\n_.max(stooges, function(stooge){ return stooge.age; });\n=> {name: 'curly', age: 60};\n","min","_.min(list, [iteratee], [context])","\n Returns the minimum value in ","Infinity","\nvar numbers = [10, 5, 100, 2, 1000];\n_.min(numbers);\n=> 2\n","sortBy","_.sortBy(list, iteratee, [context])","\n Returns a (stably) sorted copy of ",", ranked in ascending\n order by the results of running each value through ",".\n iteratee may also be the string name of the property to sort by (eg.\n ","). This function uses operator ","\n_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });\n=> [5, 4, 6, 3, 1, 2]\n\nvar stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];\n_.sortBy(stooges, 'name');\n=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];\n","groupBy","_.groupBy(list, iteratee, [context])","\n Splits a collection into sets, grouped by the result of running each\n value through "," is a string instead of\n a function, groups by the property named by "," on each of\n the values.\n ","\n_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });\n=> {1: [1.3], 2: [2.1, 2.4]}\n\n_.groupBy(['one', 'two', 'three'], 'length');\n=> {3: [\"one\", \"two\"], 5: [\"three\"]}\n","indexBy","_.indexBy(list, iteratee, [context])","\n Given a ",", and an "," function\n that returns a key for each element in the list (or a property name),\n returns an object with an index of each item.\n Just like ",", but for when you know your\n keys are unique.\n ","\nvar stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];\n_.indexBy(stooges, 'age');\n=> {\n \"40\": {name: 'moe', age: 40},\n \"50\": {name: 'larry', age: 50},\n \"60\": {name: 'curly', age: 60}\n}\n","countBy","_.countBy(list, iteratee, [context])","\n Sorts a list into groups and returns a count for the number of objects\n in each group.\n Similar to ",", but instead of returning a list of values,\n returns a count for the number of values in that group.\n ","\n_.countBy([1, 2, 3, 4, 5], function(num) {\n return num % 2 == 0 ? 'even': 'odd';\n});\n=> {odd: 3, even: 2}\n","shuffle","_.shuffle(list)","\n Returns a shuffled copy of the ",", using a version of the\n ","Fisher-Yates shuffle","\n_.shuffle([1, 2, 3, 4, 5, 6]);\n=> [4, 1, 6, 3, 5, 2]\n","sample","_.sample(list, [n])","\n Produce a random sample from the ",". Pass a number to\n return ","n"," random elements from the list. Otherwise a single random\n item will be returned.\n ","\n_.sample([1, 2, 3, 4, 5, 6]);\n=> 4\n\n_.sample([1, 2, 3, 4, 5, 6], 3);\n=> [1, 6, 2]\n","toArray","_.toArray(list)","\n Creates a real Array from the "," (anything that can be\n iterated over). Useful for transmuting the "," object.\n ","\n(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);\n=> [2, 3, 4]\n","size","_.size(list)","\n Return the number of values in the ","\n_.size([1, 2, 3, 4, 5]);\n=> 5\n\n_.size({one: 1, two: 2, three: 3});\n=> 3\n","partition","_.partition(list, predicate)","\n Split "," into two arrays: one whose elements all satisfy\n "," and one whose elements all do not satisfy ","\n_.partition([0, 1, 2, 3, 4, 5], isOdd);\n=> [[1, 3, 5], [0, 2, 4]]\n","compact","_.compact(list)","\n Returns a copy of the "," with all falsy values removed.\n In JavaScript, ","false","null","0","\"\"",",\n ","NaN"," are all falsy.\n ","\n_.compact([0, 1, false, 2, '', 3]);\n=> [1, 2, 3]\n","Array Functions","\n Note: All array functions will also work on the arguments object.\n However, Underscore functions are not designed to work on \"sparse\" arrays.\n ","_.first(array, [n])","Aliases: head, take","\n Returns the first element of an ","array",". Passing "," will\n return the first "," elements of the array.\n ","\n_.first([5, 4, 3, 2, 1]);\n=> 5\n","initial","_.initial(array, [n])","\n Returns everything but the last entry of the array. Especially useful on\n the arguments object. Pass "," to exclude the last "," elements\n from the result.\n ","\n_.initial([5, 4, 3, 2, 1]);\n=> [5, 4, 3, 2]\n","last","_.last(array, [n])","\n Returns the last element of an "," will return\n the last ","\n_.last([5, 4, 3, 2, 1]);\n=> 1\n","rest","_.rest(array, [index])","Aliases: tail, drop","\n Returns the "," of the elements in an array. Pass an ","\n to return the values of the array from that index onward.\n ","\n_.rest([5, 4, 3, 2, 1]);\n=> [4, 3, 2, 1]\n","flatten","_.flatten(array, [depth])","\n Flattens a nested ",". If you pass "," or ","1","\n as the ","depth",", the array will only be flattened a single level.\n Passing a greater number will cause the flattening to descend deeper\n into the nesting hierarchy. Omitting the "," argument, or\n passing ",", flattens the array all the\n way to the deepest nesting level.\n ","\n_.flatten([1, [2], [3, [[4]]]]);\n=> [1, 2, 3, 4];\n\n_.flatten([1, [2], [3, [[4]]]], true);\n=> [1, 2, 3, [[4]]];\n\n_.flatten([1, [2], [3, [[4]]]], 2);\n=> [1, 2, 3, [4]];\n","without","_.without(array, *values)"," with all instances of the ","values","\n removed.\n ","\n_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);\n=> [2, 3, 4]\n","union","_.union(*arrays)","\n Computes the union of the passed-in ","arrays",": the list of unique items,\n in order, that are present in one or more of the ","\n_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);\n=> [1, 2, 3, 101, 10]\n","intersection","_.intersection(*arrays)","\n Computes the list of values that are the intersection of all the ",".\n Each value in the result is present in each of the ","\n_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);\n=> [1, 2]\n","difference","_.difference(array, *others)","\n Similar to ",", but returns the values from "," that\n are not present in the ","other"," arrays.\n ","\n_.difference([1, 2, 3, 4, 5], [5, 2, 10]);\n=> [1, 3, 4]\n","uniq","_.uniq(array, [isSorted], [iteratee])","Alias: unique","\n Produces a duplicate-free version of the ",", using ","==="," to test\n object equality. In particular only the first occurrence of each value is kept.\n If you know in advance that the "," is sorted,\n passing "," for ","isSorted"," will run a much faster algorithm.\n If you want to compute unique items based on a transformation, pass an\n "," function.\n ","\n_.uniq([1, 2, 1, 4, 1, 3]);\n=> [1, 2, 4, 3]\n","zip","_.zip(*arrays)","\n Merges together the values of each of the "," with the\n values at the corresponding position. Useful when you have separate\n data sources that are coordinated through matching array indexes.\n ","\n_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);\n=> [[\"moe\", 30, true], [\"larry\", 40, false], [\"curly\", 50, false]]\n\n","unzip","_.unzip(array)","Alias: transpose","\n The opposite of ",". Given an "," of\n arrays, returns a series of new arrays, the first of which contains all\n of the first elements in the input arrays, the second of which contains\n all of the second elements, and so on. If you're working with a matrix\n of nested arrays, this can be used to transpose the matrix.\n ","\n_.unzip([[\"moe\", 30, true], [\"larry\", 40, false], [\"curly\", 50, false]]);\n=> [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]]\n","object","_.object(list, [values])","\n Converts arrays into objects. Pass either a single list of\n ","[key, value]"," pairs, or a list of keys, and a list of values. Passing\n by pairs is the reverse of ","pairs",". If duplicate keys exist,\n the last value wins.\n ","\n_.object(['moe', 'larry', 'curly'], [30, 40, 50]);\n=> {moe: 30, larry: 40, curly: 50}\n\n_.object([['moe', 30], ['larry', 40], ['curly', 50]]);\n=> {moe: 30, larry: 40, curly: 50}\n","chunk","_.chunk(array, length)","\n Chunks an "," into multiple arrays, each containing ","\n or fewer items.\n ","\nvar partners = _.chunk(_.shuffle(kindergarten), 2);\n=> [[\"Tyrone\", \"Elie\"], [\"Aidan\", \"Sam\"], [\"Katrina\", \"Billie\"], [\"Little Timmy\"]]\n","_.indexOf(array, value, [isSorted])","\n Returns the index at which "," can be found in the ",",\n or ","-1"," if value is not present in the ",". If you're working with a\n large array, and you know that the array is already sorted, pass ","\n for "," to use a faster binary search ... or, pass a number as\n the third argument in order to look for the first matching value in the\n array after the given index. If "," is ",",\n this function uses operator ","\n_.indexOf([1, 2, 3], 2);\n=> 1\n","lastIndexOf","_.lastIndexOf(array, value, [fromIndex])","\n Returns the index of the last occurrence of "," in the "," if value is not present. Pass "," to start your search at a\n given index.\n ","\n_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);\n=> 4\n","sortedIndex","_.sortedIndex(array, value, [iteratee], [context])","\n Uses a binary search to determine the smallest index at which the ","should"," be inserted into the "," in order to maintain the ","'s\n sorted order. If an "," function is provided,\n it will be used to compute the sort ranking of each value, including the "," you pass.\n The iteratee may also be the string name of the property to sort by\n (eg. ","\n_.sortedIndex([10, 20, 30, 40, 50], 35);\n=> 3\n\nvar stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];\n_.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');\n=> 1\n","findIndex","_.findIndex(array, predicate, [context])","_.indexOf",", returns the first index\n where the "," truth test passes; otherwise returns ","\n_.findIndex([4, 6, 8, 12], isPrime);\n=> -1 // not found\n_.findIndex([4, 6, 7, 12], isPrime);\n=> 2\n","findLastIndex","_.findLastIndex(array, predicate, [context])","\n Like ","_.findIndex"," but iterates the array in reverse,\n returning the index closest to the end where the "," truth test\n passes.\n ","\nvar users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},\n {'id': 2, 'name': 'Ted', 'last': 'White'},\n {'id': 3, 'name': 'Frank', 'last': 'James'},\n {'id': 4, 'name': 'Ted', 'last': 'Jones'}];\n_.findLastIndex(users, {\n name: 'Ted'\n});\n=> 3\n","range","_.range([start], stop, [step])","\n A function to create flexibly-numbered lists of integers, handy for\n "," loops. ","start",", if omitted,\n defaults to ","; ","step"," defaults to "," if ","\n is before ","stop",", otherwise ",". Returns a list\n of integers from "," (inclusive) to "," (exclusive),\n incremented (or decremented) by ","\n_.range(10);\n=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n_.range(1, 11);\n=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n_.range(0, 30, 5);\n=> [0, 5, 10, 15, 20, 25]\n_.range(0, -10, -1);\n=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n_.range(0);\n=> []\n","Function (uh, ahem) Functions","bind","_.bind(function, object, *arguments)","\n Bind a ","function"," to an ",", meaning that whenever\n the function is called, the value of ","this"," will be the ",".\n Optionally, pass "," to the "," to pre-fill them,\n also known as ","partial application",". For partial application without\n context binding, use ","partial","\nvar func = function(greeting){ return greeting + ': ' + this.name };\nfunc = _.bind(func, {name: 'moe'}, 'hi');\nfunc();\n=> 'hi: moe'\n","bindAll","_.bindAll(object, *methodNames)","\n Binds a number of methods on the ",", specified by\n ","methodNames",", to be run in the context of that object whenever they\n are invoked. Very handy for binding functions that are going to be used\n as event handlers, which would otherwise be invoked with a fairly useless\n "," are required.\n ","\nvar buttonView = {\n label : 'underscore',\n onClick: function(){ alert('clicked: ' + this.label); },\n onHover: function(){ console.log('hovering: ' + this.label); }\n};\n_.bindAll(buttonView, 'onClick', 'onHover');\n// When the button is clicked, this.label will have the correct value.\njQuery('#underscore_button').on('click', buttonView.onClick);\n","_.partial(function, *arguments)","\n Partially apply a function by filling in any number of its\n "," changing its dynamic ","\n value. A close cousin of ",". You may pass\n ","_"," in your list of "," to specify an argument that\n should not be pre-filled, but left open to supply at call-time.\n ","Note: if you need "," placeholders and a ","\n binding at the same time, use both ","_.partial","_.bind","\nvar subtract = function(a, b) { return b - a; };\nsub5 = _.partial(subtract, 5);\nsub5(20);\n=> 15\n\n// Using a placeholder\nsubFrom20 = _.partial(subtract, _, 20);\nsubFrom20(5);\n=> 15\n","memoize","_.memoize(function, [hashFunction])","\n Memoizes a given "," by caching the computed result. Useful\n for speeding up slow-running computations. If passed an optional\n ","hashFunction",", it will be used to compute the hash key for storing\n the result, based on the arguments to the original function. The default\n "," just uses the first argument to the memoized function\n as the key. The cache of memoized values is available as the ","cache","\n property on the returned function.\n ","\nvar fibonacci = _.memoize(function(n) {\n return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);\n});\n","delay","_.delay(function, wait, *arguments)","\n Much like ","setTimeout",", invokes "," after ","wait","\n milliseconds. If you pass the optional ",", they will be\n forwarded on to the "," when it is invoked.\n ","\nvar log = _.bind(console.log, console);\n_.delay(log, 1000, 'logged later');\n=> 'logged later' // Appears after one second.\n","defer","_.defer(function, *arguments)","\n Defers invoking the "," until the current call stack has cleared,\n similar to using "," with a delay of 0. Useful for performing\n expensive computations or HTML rendering in chunks without blocking the UI thread\n from updating. If you pass the optional ","\n_.defer(function(){ alert('deferred'); });\n// Returns from the function before the alert runs.\n","throttle","_.throttle(function, wait, [options])","\n Creates and returns a new, throttled version of the passed function,\n that, when invoked repeatedly, will only actually call the original function\n at most once per every ","\n milliseconds. Useful for rate-limiting events that occur faster than you\n can keep up with.\n ","\n By default, "," will execute the function as soon as you call it\n for the first time, and, if you call it again any number of times\n during the "," period, as soon as that period is over.\n If you'd like to disable the leading-edge\n call, pass ","{leading: false}",", and if you'd like to disable the\n execution on the trailing-edge, pass ","{trailing: false}","\nvar throttled = _.throttle(updatePosition, 100);\n$(window).scroll(throttled);\n","\n If you need to cancel a scheduled throttle, you can call ",".cancel()","\n on the throttled function.\n ","debounce","_.debounce(function, wait, [immediate])","\n Creates and returns a new debounced version of the passed function which\n will postpone its execution until after\n "," milliseconds have elapsed since the last time it\n was invoked. Useful for implementing behavior that should only happen\n ","after"," the input has stopped arriving. For example: rendering a\n preview of a Markdown comment, recalculating a layout after the window\n has stopped being resized, and so on.\n ","\n At the end of the wait interval, the function will be called\n with the arguments that were passed most recently to the\n debounced function.\n ","\n Pass "," for the ","immediate"," argument to cause\n "," to trigger the function on the leading instead of the\n trailing edge of the "," interval. Useful in circumstances like\n preventing accidental double-clicks on a \"submit\" button from firing a\n second time.\n ","\nvar lazyLayout = _.debounce(calculateLayout, 300);\n$(window).resize(lazyLayout);\n","\n If you need to cancel a scheduled debounce, you can call ","\n on the debounced function.\n ","once","_.once(function)","\n Creates a version of the function that can only be called one time.\n Repeated calls to the modified function will have no effect, returning\n the value from the original call. Useful for initialization functions,\n instead of having to set a boolean flag and then check it later.\n ","\nvar initialize = _.once(createApplication);\ninitialize();\ninitialize();\n// Application is only created once.\n","_.after(count, function)","\n Creates a wrapper of "," that does nothing at first. From\n the ","count","-th call onwards, it starts actually calling\n ",". Useful for grouping asynchronous responses, where you\n want to be sure that all the async calls have finished, before\n proceeding.\n ","\nvar renderNotes = _.after(notes.length, render);\n_.each(notes, function(note) {\n note.asyncSave({success: renderNotes});\n});\n// renderNotes is run once, after all notes have saved.\n","before","_.before(count, function)"," that memoizes its return value.\n From the ","-th call onwards, the memoized result of the last\n invocation is returned immediately instead of invoking ","\n again. So the wrapper will invoke "," at most ","\n - 1 times.\n ","\nvar monthlyMeeting = _.before(3, askForRaise);\nmonthlyMeeting();\nmonthlyMeeting();\nmonthlyMeeting();\n// the result of any subsequent calls is the same as the second call\n","wrap","_.wrap(function, wrapper)","\n Wraps the first "," inside of the ","wrapper"," function,\n passing it as the first argument. This allows the "," to\n execute code before and after the "," runs, adjust the arguments,\n and execute it conditionally.\n ","\nvar hello = function(name) { return \"hello: \" + name; };\nhello = _.wrap(hello, function(func) {\n return \"before, \" + func(\"moe\") + \", after\";\n});\nhello();\n=> 'before, hello: moe, after'\n","negate","_.negate(predicate)","\n Returns a new negated version of the ","\nvar isFalsy = _.negate(Boolean);\n_.find([-2, -1, 0, 1, 2], isFalsy);\n=> 0\n","compose","_.compose(*functions)","\n Returns the composition of a list of ","functions",", where each function\n consumes the return value of the function that follows. In math terms,\n composing the functions ","f()","g()",", and ","h()"," produces\n ","f(g(h()))","\nvar greet = function(name){ return \"hi: \" + name; };\nvar exclaim = function(statement){ return statement.toUpperCase() + \"!\"; };\nvar welcome = _.compose(greet, exclaim);\nwelcome('moe');\n=> 'hi: MOE!'\n","restArguments","_.restArguments(function, [startIndex])","\n Returns a version of the "," that, when called, receives all\n arguments from and beyond ","startIndex"," collected into a single array.\n If you don’t pass an explicit ",", it will be determined by\n looking at the number of arguments to the "," itself. Similar\n to ES6’s ","rest\n parameters syntax","\nvar raceResults = _.restArguments(function(gold, silver, bronze, everyoneElse) {\n _.each(everyoneElse, sendConsolations);\n});\n\nraceResults(\"Dopey\", \"Grumpy\", \"Happy\", \"Sneezy\", \"Bashful\", \"Sleepy\", \"Doc\");\n","Object Functions","keys","_.keys(object)","\n Retrieve all the names of the ","'s own enumerable properties.\n ","\n_.keys({one: 1, two: 2, three: 3});\n=> [\"one\", \"two\", \"three\"]\n","allKeys","_.allKeys(object)","\n Retrieve ","all"," the names of ","'s own and inherited properties.\n ","\nfunction Stooge(name) {\n this.name = name;\n}\nStooge.prototype.silly = true;\n_.allKeys(new Stooge(\"Moe\"));\n=> [\"name\", \"silly\"]\n","_.values(object)","\n Return all of the values of the ","'s own properties.\n ","\n_.values({one: 1, two: 2, three: 3});\n=> [1, 2, 3]\n","mapObject","_.mapObject(object, iteratee, [context])",", but for objects. Transform the value\n of each property in turn.\n ","\n_.mapObject({start: 5, end: 12}, function(val, key) {\n return val + 5;\n});\n=> {start: 10, end: 17}\n","_.pairs(object)","\n Convert an object into a list of "," pairs. The opposite\n of ","\n_.pairs({one: 1, two: 2, three: 3});\n=> [[\"one\", 1], [\"two\", 2], [\"three\", 3]]\n","invert","_.invert(object)"," where the keys have become the values\n and the values the keys. For this to work, all of your object's values\n should be unique and string serializable.\n ","\n_.invert({Moe: \"Moses\", Larry: \"Louis\", Curly: \"Jerome\"});\n=> {Moses: \"Moe\", Louis: \"Larry\", Jerome: \"Curly\"};\n","create","_.create(prototype, props)","\n Creates a new object with the given prototype, optionally attaching\n ","props"," as ","own"," properties. Basically, ","Object.create",",\n but without all of the property descriptor jazz.\n ","\nvar moe = _.create(Stooge.prototype, {name: \"Moe\"});\n","_.functions(object)","Alias: methods","\n Returns a sorted list of the names of every method in an object —\n that is to say, the name of every function property of the object.\n ","\n_.functions(_);\n=> [\"all\", \"any\", \"bind\", \"bindAll\", \"clone\", \"compact\", \"compose\" ...\n","findKey","_.findKey(object, predicate, [context])"," but for keys in objects.\n Returns the "," where the "," truth test\n passes or ","extend","_.extend(destination, *sources)","\n Shallowly copy all of the properties ","in"," the "," objects over to the\n ","destination"," object, and return the "," object.\n Any nested objects or arrays will be copied by reference, not duplicated.\n It's in-order, so the last source will override properties of the same\n name in previous arguments.\n ","\n_.extend({name: 'moe'}, {age: 50});\n=> {name: 'moe', age: 50}\n","extendOwn","_.extendOwn(destination, *sources)","Alias: assign",", but only copies "," properties over to the\n destination object.\n ","pick","_.pick(object, *keys)","\n Return a copy of the ",", filtered to only have values for\n the allowed "," (or array of valid keys). Alternatively\n accepts a predicate indicating which keys to pick.\n ","\n_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');\n=> {name: 'moe', age: 50}\n_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {\n return _.isNumber(value);\n});\n=> {age: 50}\n","omit","_.omit(object, *keys)",", filtered to omit the disallowed\n "," (or array of keys). Alternatively accepts a predicate\n indicating which keys to omit.\n ","\n_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');\n=> {name: 'moe', age: 50}\n_.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {\n return _.isNumber(value);\n});\n=> {name: 'moe', userid: 'moe1'}\n","defaults","_.defaults(object, *defaults)"," after filling in its "," properties\n with the first value present in the following list of "," objects.\n ","\nvar iceCream = {flavor: \"chocolate\"};\n_.defaults(iceCream, {flavor: \"vanilla\", sprinkles: \"lots\"});\n=> {flavor: \"chocolate\", sprinkles: \"lots\"}\n","clone","_.clone(object)","\n Create a shallow-copied clone of the provided ","plain",".\n Any nested objects or arrays will be copied by reference, not duplicated.\n ","\n_.clone({name: 'moe'});\n=> {name: 'moe'};\n","tap","_.tap(object, interceptor)","\n Invokes ","interceptor"," with the ",", and then returns ",".\n The primary purpose of this method is to \"tap into\" a method chain, in order to perform operations on intermediate results within the chain.\n ","\n_.chain([1,2,3,200])\n .filter(function(num) { return num % 2 == 0; })\n .tap(alert)\n .map(function(num) { return num * num })\n .value();\n=> // [2, 200] (alerted)\n=> [4, 40000]\n","toPath","_.toPath(path)","\n Ensures that ","path"," is an array. If "," is a string, it is\n wrapped in a single-element array; if it is an array already, it is\n returned unmodified.\n ","\n_.toPath('key');\n=> ['key']\n_.toPath(['a', 0, 'b']);\n=> ['a', 0, 'b'] // (same array)\n","_.toPath"," is used internally in ","has","get","property","propertyOf","result",", as well as in ","\n and all functions that depend on it, in order to normalize deep\n property paths. You can override "," if you want to\n customize this behavior, for example to enable Lodash-like string path\n shorthands. Be advised that altering "," will unavoidably\n cause some keys to become unreachable; override at your own risk.\n ","\n// Support dotted path shorthands.\nvar originalToPath = _.toPath;\n_.mixin({\n toPath: function(path) {\n return _.isString(path) ? path.split('.') : originalToPath(path);\n }\n});\n_.get({a: [{b: 5}]}, 'a.0.b');\n=> 5\n","_.get(object, path, [default])","\n Returns the specified property of "," may be\n specified as a simple key, or as an array of object keys or array\n indexes, for deep property fetching. If the property does not exist or\n is ",", the optional ","default"," is returned.\n ","\n_.get({a: 10}, 'a');\n=> 10\n_.get({a: [{b: 2}]}, ['a', 0, 'b']);\n=> 2\n_.get({a: 10}, 'b', 100);\n=> 100\n","_.has(object, key)","\n Does the object contain the given key? Identical to\n ","object.hasOwnProperty(key)",", but uses a safe reference to the\n ","hasOwnProperty"," function, in case it's been\n\n ","overridden accidentally","\n_.has({a: 1, b: 2, c: 3}, \"b\");\n=> true\n","_.property(path)","\n Returns a function that will return the specified property of any\n passed-in object. "," may be specified as a simple key, or\n as an array of object keys or array indexes, for deep property fetching.\n ","\nvar stooge = {name: 'moe'};\n'moe' === _.property('name')(stooge);\n=> true\n\nvar stooges = {moe: {fears: {worst: 'Spiders'}}, curly: {fears: {worst: 'Moe'}}};\nvar curlysWorstFear = _.property(['curly', 'fears', 'worst']);\ncurlysWorstFear(stooges);\n=> 'Moe'\n","_.propertyOf(object)","\n Inverse of ","_.property",". Takes an object and returns a function\n which will return the value of a provided property.\n ","\nvar stooge = {name: 'moe'};\n_.propertyOf(stooge)('name');\n=> 'moe'","matcher","_.matcher(attrs)","Alias: matches","\n Returns a predicate function that will tell you if a passed in object\n contains all of the key/value properties present in ","attrs","\nvar ready = _.matcher({selected: true, visible: true});\nvar readyToGoList = _.filter(list, ready);","isEqual","_.isEqual(object, other)","\n Performs an optimized deep comparison between the two objects, to determine\n if they should be considered equal.\n ","\nvar stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};\nvar clone = {name: 'moe', luckyNumbers: [13, 27, 34]};\nstooge == clone;\n=> false\n_.isEqual(stooge, clone);\n=> true\n","isMatch","_.isMatch(object, properties)","\n Tells you if the keys and values in "," are contained\n in ","\nvar stooge = {name: 'moe', age: 32};\n_.isMatch(stooge, {age: 32});\n=> true\n","_.isEmpty(collection)","collection"," has no elements. For strings\n and array-like objects ","_.isEmpty"," checks if the length property\n is 0. For other objects, it returns "," if the object has no\n enumerable own-properties. Note that primitive numbers, booleans and\n symbols are always empty by this definition.\n ","\n_.isEmpty([1, 2, 3]);\n=> false\n_.isEmpty({});\n=> true\n","isElement","_.isElement(object)"," is a DOM element.\n ","\n_.isElement(jQuery('body')[0]);\n=> true\n","isArray","_.isArray(object)"," is an Array.\n ","\n(function(){ return _.isArray(arguments); })();\n=> false\n_.isArray([1,2,3]);\n=> true\n","isObject","_.isObject(value)"," is an Object. Note that JavaScript\n arrays and functions are objects, while (normal) strings and numbers are not.\n ","\n_.isObject({});\n=> true\n_.isObject(1);\n=> false\n","isArguments","_.isArguments(object)"," is an Arguments object.\n ","\n(function(){ return _.isArguments(arguments); })(1, 2, 3);\n=> true\n_.isArguments([1,2,3]);\n=> false\n","isFunction","_.isFunction(object)"," is a Function.\n ","\n_.isFunction(alert);\n=> true\n","isString","_.isString(object)"," is a String.\n ","\n_.isString(\"moe\");\n=> true\n","isNumber","_.isNumber(object)"," is a Number (including ","\n_.isNumber(8.4 * 5);\n=> true\n","isFinite","_.isFinite(object)"," is a finite Number.\n ","\n_.isFinite(-101);\n=> true\n\n_.isFinite(-Infinity);\n=> false\n","isBoolean","_.isBoolean(object)"," is either ","\n_.isBoolean(null);\n=> false\n","isDate","_.isDate(object)"," is a Date.\n ","\n_.isDate(new Date());\n=> true\n","isRegExp","_.isRegExp(object)"," is a RegExp.\n ","\n_.isRegExp(/moe/);\n=> true\n","isError","_.isError(object)"," inherits from an Error.\n ","\ntry {\n throw new TypeError(\"Example\");\n} catch (o_O) {\n _.isError(o_O);\n}\n=> true\n","isSymbol","_.isSymbol(object)"," is a ","Symbol","\n_.isSymbol(Symbol());\n=> true\n","isMap","_.isMap(object)","Map","\n_.isMap(new Map());\n=> true\n","isWeakMap","_.isWeakMap(object)","WeakMap","\n_.isWeakMap(new WeakMap());\n=> true\n","isSet","_.isSet(object)","Set","\n_.isSet(new Set());\n=> true\n","isWeakSet","_.isWeakSet(object)","WeakSet","\n_.isWeakSet(WeakSet());\n=> true\n","isArrayBuffer","_.isArrayBuffer(object)"," is an ","ArrayBuffer","\n_.isArrayBuffer(new ArrayBuffer(8));\n=> true\n","isDataView","_.isDataView(object)","DataView","\n_.isDataView(new DataView(new ArrayBuffer(8)));\n=> true\n","isTypedArray","_.isTypedArray(object)","TypedArray","\n_.isTypedArray(new Int8Array(8));\n=> true\n","isNaN","_.isNaN(object)"," Note: this is not\n the same as the native "," function, which will also return\n true for many other not-number values, such as ","\n_.isNaN(NaN);\n=> true\nisNaN(undefined);\n=> true\n_.isNaN(undefined);\n=> false\n","isNull","_.isNull(object)"," if the value of ","\n_.isNull(null);\n=> true\n_.isNull(undefined);\n=> false\n","isUndefined","_.isUndefined(value)","\n_.isUndefined(window.missingVariable);\n=> true\n","Utility Functions","noConflict","_.noConflict()","\n Give control of the global "," variable back to its previous\n owner. Returns a reference to the ","Underscore","\nvar underscore = _.noConflict();\n","\n The ","_.noConflict"," function is not present if you use the EcmaScript 6, AMD or CommonJS module system to import Underscore.\n ","identity","_.identity(value)","\n Returns the same value that is used as the argument. In math:\n ","f(x) = x","\n This function looks useless, but is used throughout Underscore as\n a default iteratee.\n ","\nvar stooge = {name: 'moe'};\nstooge === _.identity(stooge);\n=> true\n","constant","_.constant(value)","\n Creates a function that returns the same value that is used as the\n argument of ","_.constant","\nvar stooge = {name: 'moe'};\nstooge === _.constant(stooge)();\n=> true","noop","_.noop()"," irrespective of the arguments passed to it.\n Useful as the default for optional callback arguments.\n ","\nobj.initialize = _.noop;\n","times","_.times(n, iteratee, [context])","\n Invokes the given iteratee function "," times. Each invocation of\n "," is called with an "," argument.\n Produces an array of the returned values.\n ","\n_.times(3, function(n){ genie.grantWishNumber(n); });","random","_.random(min, max)","\n Returns a random integer between ",", inclusive.\n If you only pass one argument, it will return a number between ","\n and that number.\n ","\n_.random(0, 100);\n=> 42","mixin","_.mixin(object)","\n Allows you to extend Underscore with your own utility functions. Pass\n a hash of ","{name: function}"," definitions to have your functions\n added to the Underscore object, as well as the OOP wrapper. Returns the\n Underscore object to facilitate chaining.","\n_.mixin({\n capitalize: function(string) {\n return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();\n }\n});\n_(\"fabio\").capitalize();\n=> \"Fabio\"\n","_.iteratee(value, [context])","\n Generates a callback that can be applied to each element in\n a collection. ","_.iteratee"," supports a number of shorthand\n syntaxes for common callback use cases. Depending upon ","'s\n type, "," will return:\n ","\n// No value\n_.iteratee();\n=> _.identity()\n\n// Function\n_.iteratee(function(n) { return n * 2; });\n=> function(n) { return n * 2; }\n\n// Object\n_.iteratee({firstName: 'Chelsea'});\n=> _.matcher({firstName: 'Chelsea'});\n\n// Anything else\n_.iteratee('firstName');\n=> _.property('firstName');","\n The following Underscore methods transform their predicates through\n ",": ","\n You may overwrite "," with your own custom function,\n if you want additional or different shorthand syntaxes:\n ","\n// Support `RegExp` predicate shorthand.\nvar builtinIteratee = _.iteratee;\n_.iteratee = function(value, context) {\n if (_.isRegExp(value)) return function(obj) { return value.test(obj) };\n return builtinIteratee(value, context);\n};","uniqueId","_.uniqueId([prefix])","\n Generate a globally-unique id for client-side models or DOM elements\n that need one. If ","prefix"," is passed, the id will be appended to it.\n ","\n_.uniqueId('contact_');\n=> 'contact_104'","escape","_.escape(string)","\n Escapes a string for insertion into HTML, replacing\n ","&",">","\"","`","'"," characters.\n ","\n_.escape('Curly, Larry & Moe');\n=> \"Curly, Larry & Moe\"","unescape","_.unescape(string)",", replaces\n ","&","<",">",""","`","'","\n with their unescaped counterparts.\n ","\n_.unescape('Curly, Larry & Moe');\n=> \"Curly, Larry & Moe\"","_.result(object, property, [defaultValue])","\n If the value of the named "," is a function then invoke it\n with the "," as context; otherwise, return it. If a default value\n is provided and the property doesn't exist or is undefined then the default\n will be returned. If ","defaultValue"," is a function its result will be returned.\n ","\nvar object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};\n_.result(object, 'cheese');\n=> \"crumpets\"\n_.result(object, 'stuff');\n=> \"nonsense\"\n_.result(object, 'meat', 'ham');\n=> \"ham\"\n","now","_.now()","\n Returns an integer timestamp for the current time, using the fastest\n method available in the runtime. Useful for implementing timing/animation\n functions.\n ","\n_.now();\n=> 1392066795351\n","template","_.template(templateString, [settings])","\n Compiles JavaScript templates into functions that can be evaluated\n for rendering. Useful for rendering complicated bits of HTML from JSON\n data sources. Template functions can both interpolate values, using\n ","<%= … %>",", as well as execute arbitrary JavaScript code, with\n ","<% … %>",". If you wish to interpolate a value, and have\n it be HTML-escaped, use ","<%- … %>",". When you evaluate a\n template function, pass in a ","data"," object that has properties\n corresponding to the template's free variables. The ","settings"," argument\n should be a hash containing any ","_.templateSettings"," that should be overridden.\n ","\nvar compiled = _.template(\"hello: <%= name %>\");\ncompiled({name: 'moe'});\n=> \"hello: moe\"\n\nvar template = _.template(\"<%- value %>\");\ntemplate({value: '","Object-Oriented Style","\n You can use Underscore in either an object-oriented or a functional style,\n depending on your preference. The following two lines of code are\n identical ways to double a list of numbers.\n source,\n source\n ","\n_.map([1, 2, 3], function(n){ return n * 2; });\n_([1, 2, 3]).map(function(n){ return n * 2; });","Chaining","\n Calling ","chain"," will cause all future method calls to return\n wrapped objects. When you've finished the computation, call\n "," to retrieve the final value. Here's an example of chaining\n together a ","map/flatten/reduce",", in order to get the word count of\n every word in a song.\n ","\nvar lyrics = [\n {line: 1, words: \"I'm a lumberjack and I'm okay\"},\n {line: 2, words: \"I sleep all night and I work all day\"},\n {line: 3, words: \"He's a lumberjack and he's okay\"},\n {line: 4, words: \"He sleeps all night and he works all day\"}\n];\n\n_.chain(lyrics)\n .map(function(line) { return line.words.split(' '); })\n .flatten()\n .reduce(function(counts, word) {\n counts[word] = (counts[word] || 0) + 1;\n return counts;\n }, {})\n .value();\n\n=> {lumberjack: 2, all: 4, night: 2 ... }","\n In addition, the\n ","Array prototype's methods","\n are proxied through the chained Underscore object, so you can slip a\n ","reverse"," or a ","push"," into your chain, and continue to\n modify the array.\n ","_.chain(obj)","\n Returns a wrapped object. Calling methods on this object will continue\n to return wrapped objects until "," is called.\n ","\nvar stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];\nvar youngest = _.chain(stooges)\n .sortBy(function(stooge){ return stooge.age; })\n .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })\n .first()\n .value();\n=> \"moe is 21\"\n","_.chain(obj).value()","\n Extracts the value of a wrapped object.\n ","\n_.chain([1, 2, 3]).reverse().value();\n=> [3, 2, 1]\n","Links & Suggested Reading","\n Underscore.lua,\n a Lua port of the functions that are applicable in both languages.\n Includes OOP-wrapping and chaining.\n (source)\n ","\n Dollar.swift, a Swift port\n of many of the Underscore.js functions and more.\n (source)\n ","\n Underscore.m, an Objective-C port\n of many of the Underscore.js functions, using a syntax that encourages\n chaining.\n (source)\n ","\n _.m, an alternative\n Objective-C port that tries to stick a little closer to the original\n Underscore.js API.\n (source)\n ","\n Underscore.php,\n a PHP port of the functions that are applicable in both languages.\n Tailored for PHP 5.4 and made with data-type tolerance in mind.\n (source)\n ","\n Underscore-perl,\n a Perl port of many of the Underscore.js functions,\n aimed at on Perl hashes and arrays.\n (source)\n ","\n Underscore.cfc,\n a Coldfusion port of many of the Underscore.js functions.\n (source)\n ","Underscore.string",",\n an Underscore extension that adds functions for string-manipulation:\n ","trim","startsWith","capitalize","sprintf",", and more.\n ","\n Underscore-java,\n a java port of the functions that are applicable in both languages.\n Includes OOP-wrapping and chaining.\n (source)\n ","\n Ruby's Enumerable module.\n ","\n Prototype.js, which provides\n JavaScript with collection functions in the manner closest to Ruby's Enumerable.\n ","\n Oliver Steele's\n Functional JavaScript,\n which includes comprehensive higher-order function support as well as string lambdas.\n ","\n Michael Aufreiter's Data.js,\n a data manipulation + persistence library for JavaScript.\n ","\n Python's itertools.\n ","\n PyToolz, a Python port\n that extends itertools and functools to include much of the\n Underscore API.\n ","\n Funcy, a practical\n collection of functional helpers for Python, partially inspired by Underscore.\n ","Notes","On the use of "," in Underscore","\n Underscore functions that depend on ordering, such as\n ","_.sortBy","_.sortedIndex",", use\n JavaScript’s built-in\n ","relational operators",",\n specifically the “less than” operator ",". It is\n important to understand that these operators are only meaningful for\n numbers and strings. You can throw any value to them, but JavaScript\n will convert the operands to string or number first before performing\n the actual comparison. If you pass an operand that\n cannot be meaningfully converted to string or number, it ends up being\n "," by default. This value is unsortable.\n ","\n Ideally, the values that you are sorting should either be all\n (meaningfully convertible to) strings or all (meaningfully convertible\n to) numbers. If this is not the case, you have two options:\n ","_.filter"," out all unsortable values\n first.\n ","\n Pick a target type, i.e., either string or number, and pass an\n "," to your Underscore\n function that will convert its argument to a sensible instance of\n the target type. For example, if you have an array of numbers that\n you want to sort and that may occasionally contain "," or\n ",", you can control whether you want to sort these\n before or after all numbers by passing an "," to\n "," that returns ","+Infinity"," for such values, respectively. Or maybe you want\n to treat them as zeros; it is up to you. The same ","\n can also be passed to other Underscore functions to ensure that the\n behavior is consistent.\n ","Change Log","\n 1.13.7July 24, 2024DiffDocs
\n ","\n Fixes a bug where Underscore might throw an error on load if the\n executing environment overrides the native ",".\n ","\n Adds a direct link to the corresponding source code for each\n function in the documentation.\n ","\n Clarifies the documentation for the "," argument of\n the "," function.\n ","\n Adds dark mode support to the home page.\n ","\n Other infrastructural improvements to funding, testing and building.\n ","1.13.6"," — ","September 24, 2022","Diff","Docs","\n Hotfix for version 1.13.5 to remove a ","postinstall"," script from\n the package.json, which unexpectedly broke many people's builds.\n ","\n 1.13.5September 23, 2022DiffDocs
\n ","\n Adds a ","module"," sub-entry to the package.json’s ","exports.require"," condition. When a bundling tool, such as Rollup with recent versions of ","@rollup/plugin-node-resolve",", takes the exports map very literally, this should prevent situations in which the final bundle includes multiple copies of Underscore in different module formats.\n ","\n Updates to the testing infrastructure and development dependencies.\n ","\n No code changes.\n ","\n 1.13.4June 2, 2022DiffDocs
\n ","\n Fixes a compatibility issue with WebPack module federation.\n ","\n Documentation improvements.\n ","\n 1.13.3April 23, 2022DiffDocs
\n ","\n Fixes a compatibility issue with ExtendScript.\n ","\n Various improvements to testing and continuous integration,\n including the addition of security scanning and a reduced carbon\n footprint.\n ","\n 1.13.2December 16, 2021DiffDocs
\n ","\n Fixes a regression introduced in 1.9.0 that caused\n ","_.sample","_.shuffle"," to no longer work on\n strings.\n ","\n Fixes an issue in IE8 compatibility code.\n ","\n Makes the website mobile-friendly.\n ","\n Various other minor documentation enhancements and a new test.\n ","\n 1.13.1April 15, 2021DiffDocs
\n ","\n Restores the ","underscore.js"," alias committed to the GitHub\n repository.\n ","\n Adds some build clarifications to the documentation.\n ","\n 1.13.0April 9, 2021DiffDocs
\n ","\n Merges the changes from the 1.13.0-0 through 1.13.0-3 preview\n releases into the main release stream following version 1.12.1. As\n of this release, ESM support is 100%.\n ","\n Adds a security policy to the documentation.\n ","\n Adds funding information to the documentation.\n ","\n 1.13.0-3March 31, 2021DiffDocs
\n ","\"module\""," exports condition to the\n ","package.json",", which should theoretically help to avoid\n duplicate code bundling with ","exports","-aware build tools.\n ","\n Re-synchronizes some comments and documentation text with the\n 1.12.x branch.\n ","\n 1.13.0-2March 15, 2021DiffDocs
\n ","\n Fixes the same security issue in ","_.template"," as the\n parallel 1.12.1 release.\n ","\n 1.12.1March 15, 2021DiffDocs
\n ","\n Fixes a security issue in "," that could enable a\n third party to inject code in compiled templates. This issue\n affects all versions of Underscore between 1.3.2 and 1.12.0,\n inclusive, as well as preview releases 1.13.0-0 and 1.13.0-1. The\n fix in this release is also included in the parallel preview\n release 1.13.0-2. ","CVE-2021-23358","\n Restores an optimization in ","_.debounce"," that was\n unintentionally lost in version 1.9.0 (same as in parallel preview\n release 1.13.0-0).\n ","\n Various test and documentation enhancements (same as in parallel\n preview releases 1.13.0-0 and 1.13.0-1).\n ","\n 1.13.0-1March 11, 2021DiffDocs
\n ","\n Fixes an issue that caused aliases to be absent among the named\n exports in the new native ESM entry point for Node.js 12+.\n ","\n More test and documentation fixes and enhancements.\n ","\n 1.13.0-0March 9, 2021DiffDocs
\n ","\n Adds experimental support for native ESM imports in Node.js. You\n can now also do named imports or even deep module imports directly\n from a Node.js process in Node.js version 12 and later. Monolithic\n imports are recommended for use in production. State (such as\n mixed-in functions) is shared between CommonJS and ESM consumers.\n ","\n Renames the UMD bundle to "," for\n consistency with the other bundle names. An alias named\n "," is retained for backwards compatibility.\n "," that was\n unintentionally lost in version 1.9.0.\n ","\n Various test and documentation enhancements.\n ","\n 1.12.0November 24, 2020DiffDocs
\n ","\n Adds the ","_.get"," functions. The latter\n can be overridden in order to customize the interpretation of deep\n property paths throughout Underscore. A future version of\n Underscore-contrib will be providing a ready-made function for this\n purpose; users will be able to opt in to string-based path\n shorthands such as ","'a.0.b'","'a[0][\"b\"]'"," by\n using that function from Underscore-contrib to override\n ","\n Fixes a bug in ","_.isEqual"," that caused typed arrays to\n compare equal when viewing different segments of the same\n underlying ","\n Improves the compatibility of ",",\n ","_.isDataView","_.isMap","_.isWeakMap"," and\n ","_.isSet"," with some older browsers, especially IE 11.\n ","\n Significantly enhances the performance of "," and\n several members of the isType family of functions.\n ","\n Speeds up "," comparison of typed arrays and\n ","s with idential ","buffer","byteOffset","byteLength","\n Restores cross-browser testing during continuous integration to its\n former glory and adds documentation about engine compatibility.\n ","\n Slims down the development dependencies for testing.\n ","\n 1.11.0August 28, 2020DiffDocsArticle
\n ","\n Puts the source of every function in a separate module, following\n up on the move to EcmaScript 6 ","export"," notation in ","version 1.10.0",". AMD and CommonJS versions of the\n function modules are provided as well. This brings perfect\n treeshaking to all users and unlocks the possibility to create\n arbitrary custom Underscore builds without code size overhead.\n ","modules/index.js"," is still present and the UMD bundle is\n still recommended for most users.","\n Since the modularization obfuscates the diff, piecewise diffs are provided below.\n ","\n Changes before modularization\n ","\n Modularization itself\n ","\n Changes after modularization\n ","\n Adds a monolithic bundle in EcmaScript 6 module format,\n ","underscore-esm.js",", as a modern alternative to the\n monolithic UMD bundle. Users who want to use ES module imports in\n the browser are advised to use this new bundle instead of\n ",", because ","\n provides the complete Underscore interface in a single download.\n ","\n Adds a modular version of the annotated source, reflecting the full\n internal structure of the primary source code.\n ","\n Adds ","_.isArrayBuffer","_.isTypedArray"," functions, as well as support for the\n corresponding value types to ","\n Adds the option to flatten arrays to a specific depth:\n ","_.flatten(anArray, 3)","_.transpose"," as an alias to ","_.unzip","\n Fixes an inconsistency where ","Array.prototype"," methods on\n the Underscore wrapper would error when the wrapped value is\n ",". These methods now perform a\n no-op on null values like the other Underscore functions.\n ","\n Fixes a bug that caused ","_.first","_.last"," to\n return ","[]"," instead of "," for empty arrays\n when used as an iteratee.\n ","\n Fixes a regression introduced in version 1.9.0 that caused\n ","_.bindAll"," to return "," instead of the\n bound object.\n ","\n Restores continuous integration testing with Travis CI.\n ","\n Replaces stigmatizing\n “whitelist”/“blacklist” terminology in\n comments and documentation by neutral\n “allowed”/“disallowed” terminology.\n ","\n Various clarifications and minor enhancements and fixes to the\n documentation, source comments and a test.\n ","\n 1.10.2March 30, 2020DiffDocs
\n ","\n Fixes a bug introduced with ","1.10.0",", while using the legacy\n Node.js require API: ","var _ = require(\"underscore\")._","\n 1.10.1March 30, 2020DiffDocs
\n ","\n Fixed relative links among the ES Modules to include the file\n extension, for web browser support.\n ","\n 1.10.0March 30, 2020DiffDocs
\n ","\n Reformats the source code to use EcmaScript 6 ","\n notation. The "," UMD bundle is now ","compiled\n from"," underlying source modules instead of ","being"," the\n source. From now on, Rollup users have the option to import from\n the underlying source module in order to enable treeshaking.\n ","\n Explicitly states in the documentation, and verifies in the\n unittests, that ","_.sortedIndex(array, value)"," always returns\n the lower bound, i.e., the smallest index, at which ","\n may be inserted in ","\n Makes the notation of the ","_.max"," unittest consistent with\n other unittests.\n ","\n Fixes a bug that would cause infinite recursion if an overridden\n implementation of "," attempted to fall back to the\n original implementation.\n ","\n Restores compatibility with EcmaScript 3 and ExtendScript.\n ","\n 1.9.2Jan 6, 2020DiffDocs
\n ","\n No code changes. Updated a test to help out\n CITGM.\n ","\n 1.9.1May 31, 2018DiffDocs
\n ","\n Fixes edge-case regressions from 1.9.0, including certain forms\n of calling "," on an empty array,\n and passing arrays as keys to ","_.countBy","_.groupBy","\n 1.9.0April 18, 2018DiffDocs
\n ","_.restArguments"," function for variadic function\n handling.\n ","_.chunk"," function for chunking up an array.\n ","_.isSymbol","_.isWeakSet"," functions.\n ","_.throttle"," return functions that now\n have a "," method, which can be used to cancel any\n scheduled calls.\n "," now accepts arrays of keys and indexes as path\n specifiers, for looking up a deep properties of a value.\n ","_.range"," now accepts negative ranges to generate descending\n arrays.\n ","\n Adds support for several environments including: WebWorkers,\n browserify and ES6 imports.\n ","\n Removes the ","component.json"," as the Component package\n management system is discontinued.\n ","\n The placeholder used for partial is now configurable by setting\n ","_.partial.placeholder"," now accepts arrays or arguments for keys.\n ","\n Three years of performance improvements.\n ","\n 1.8.3April 2, 2015DiffDocs
\n ","\n Adds an ","_.create"," method, as a slimmed down version of\n ","\n Works around an iOS bug that can improperly cause ","isArrayLike","\n to be JIT-ed. Also fixes a bug when passing "," to ","\n 1.8.2Feb. 22, 2015DiffDocs
\n ","\n Restores the previous old-Internet-Explorer edge cases changed in\n 1.8.1.\n "," argument to ","_.contains","\n 1.8.1Feb. 19, 2015DiffDocs
\n ","\n Fixes/changes some old-Internet Explorer and related edge case\n behavior. Test your app with Underscore 1.8.1 in an old IE and let\n us know how it's doing...\n ","\n 1.8.0Feb. 19, 2015DiffDocs
\n ","\n Added ","_.mapObject",", which is similar to ","_.map",", but just\n for the values in your object. (A real crowd pleaser.)\n ","_.allKeys"," which returns "," the enumerable property\n names on an object.\n ","\n Reverted a 1.7.0 change where ","_.extend"," only copied \"own\"\n properties. Hopefully this will un-break you — if it breaks you\n again, I apologize.\n ","_.extendOwn"," — a less-useful form of "," that\n only copies over \"own\" properties.\n ","_.findLastIndex"," functions,\n which nicely complement their twin-twins ","_.lastIndexOf","\n Added an ","_.isMatch"," predicate function that tells you if an\n object matches key-value properties. A kissing cousin of\n ","_.matcher","_.isError","\n Restored the "," function as the inverse of ",".\n Flip-flopping. I know.\n ","_.result"," now takes an optional fallback value (or function\n that provides the fallback value).\n ","\n Added the ","_.propertyOf"," function generator as a mirror-world\n version of ","\n Deprecated ","_.matches",". It's now known by a more harmonious\n name — ","\n Various and diverse code simplifications, changes for improved\n cross-platform compatibility, and edge case bug fixes.\n ","\n 1.7.0August 26, 2014DiffDocs
\n ","\n For consistency and speed across browsers, Underscore now ignores\n native array methods for ","forEach",". \"Sparse\" arrays are\n officially dead in Underscore.\n "," to customize the iterators used by collection\n functions. Many Underscore methods will take a string argument for easier\n ","-style lookups, an object for ","_.where","-style\n filtering, or a function as a custom callback.\n ","_.before"," as a counterpart to ","_.after","_.negate"," to invert the truth value of a passed-in\n predicate.\n ","_.noop"," as a handy empty placeholder function.\n "," now works with "," objects.\n ","_.has"," now guards against nullish objects.\n ","_.omit"," can now take an iteratee function.\n ","_.partition"," is now called with "," creates a shallow clone of your object and only iterates\n over own properties.\n ","\n Aligning better with the forthcoming ECMA6 ","Object.assign"," only iterates over the object's own properties.\n ","\n Falsy guards are no longer needed in ","_.defaults","—if the passed in argument isn't a JavaScript\n object it's just returned.\n ","\n Fixed a few edge cases in ","_.min"," to\n handle arrays containing "," (like strings or other objects)\n and ","\n Override base methods like ","\n and they'll be used internally by other Underscore functions too.\n ","\n The escape functions handle backticks (","), to deal with an\n IE ≤ 8 bug.\n ","\n For consistency, ","_.union","_.difference"," now\n only work with arrays and not variadic args.\n ","_.memoize"," exposes the cache of memoized values as a property\n on the returned function.\n ","_.pick"," accepts ","\n arguments for a more advanced callback.\n ","\n Underscore templates no longer accept an initial "," object.\n "," always returns a function now.\n ","\n Optimizations and code cleanup aplenty.\n ","\n 1.6.0February 10, 2014DiffDocs
\n ","\n Underscore now registers itself for AMD (Require.js), Bower and Component,\n as well as being a CommonJS module and a regular (Java)Script.\n An ugliness, but perhaps a necessary one.\n ",", a way to split a collection into two lists\n of results — those that pass and those that fail a particular predicate.\n ",", for easy creation of iterators that pull\n specific properties from objects. Useful in conjunction with other\n Underscore collection functions.\n ",", a function that will give you a predicate\n that can be used to tell if a given object matches a list of specified\n key/value properties.\n ",", as a higher-order ","_.identity","_.now",", an optimized way to get a timestamp — used\n internally to speed up ","\n The "," function may now be used to partially apply\n any of its arguments, by passing "," wherever you'd like a\n placeholder variable, to be filled-in later.\n ","_.each"," function now returns a reference to the list for chaining.\n ","_.keys"," function now returns an empty array for\n non-objects instead of throwing.\n ","\n … and more miscellaneous refactoring.\n ","\n 1.5.2September 7, 2013DiffDocs
\n "," function, which fits in alongside its\n cousins, ","\n Added a "," function, for sampling random elements from\n arrays.\n ","\n Some optimizations relating to functions that can be implemented\n in terms of "," (which includes, significantly,\n "," on objects). Also for "," in a tight loop.\n ","_.escape"," function no longer escapes '/'.\n ","\n 1.5.1July 8, 2013DiffDocs
\n ","\n Removed ",", as it's simply the application of ","\n to an array of arguments. Use ","_.zip.apply(_, list)"," to\n transpose instead.\n ","\n 1.5.0July 6, 2013DiffDocs
\n ","\n Added a new "," function, as the inverse of ","_.zip"," function now takes an ","options"," argument,\n allowing you to disable execution of the throttled function on either\n the ","leading","trailing"," edge.\n ","\n A source map is now supplied for easier debugging of the minified\n production build of Underscore.\n "," function now only overrides ","\n values, not "," ones.\n ","\n Removed the ability to call "," with no method name\n arguments. It's pretty much always wiser to allow the names of\n the methods you'd like to bind.\n "," with an invocation count\n of zero. The minimum number of calls is (naturally) now ","\n 1.4.4January 30, 2013DiffDocs
\n ","_.findWhere",", for finding the first element in a list\n that matches a particular set of keys and values.\n ",", for partially applying a function ","\n changing its dynamic reference to ","\n Simplified "," by removing some edge cases involving\n constructor functions. In short: don't "," your\n constructors.\n ","\n A minor optimization to ","\n Fix bug in the minified version due to the minifier incorrectly\n optimizing-away ","\n 1.4.3December 4, 2012DiffDocs
\n ","\n Improved Underscore compatibility with Adobe's JS engine that can be\n used to script Illustrator, Photoshop, and friends.\n ","\n Added a default "," iterator to "," function can now take ","array, iterator, context","\n as the argument list.\n "," function now returns the mapped array of iterator\n results.\n ","\n Simplified and fixed bugs in ","\n 1.4.2October 6, 2012DiffDocs
\n ","\n For backwards compatibility, returned to pre-1.4.0 behavior when\n passing "," to iteration functions. They now become no-ops\n again.\n ","\n 1.4.1October 1, 2012DiffDocs
\n ","\n Fixed a 1.4.0 regression in the ","\n 1.4.0September 27, 2012DiffDocs
\n "," function, for turning a JavaScript object\n into "," pairs ... as well as an ","\n function, for converting an array of "," pairs\n into an object.\n "," function, for counting the number of objects\n in a list that match a certain criteria.\n "," function, for performing a simple inversion\n of the keys and values in an object.\n "," function, for easy cases of filtering a list\n for objects with specific values.\n "," function, for filtering an object to remove\n certain keys.\n "," function, to return a random number in a\n given range.\n ","'d functions now return their last updated value,\n just like ","'d functions do.\n "," function now runs a stable sort algorithm.\n ","\n Added the optional "," option to ","\n \"Sparse\" arrays are no longer supported in Underscore iteration\n functions. Use a ","for"," loop instead (or better yet, an object).\n "," functions may now be called on\n ","very"," large arrays.\n ","\n Interpolation in templates now represents "," as the empty string.\n ","Underscore iteration functions no longer accept "," values\n as a no-op argument. You'll get an early error instead.","\n A number of edge-cases fixes and tweaks, which you can spot in the\n diff.\n Depending on how you're using Underscore, 1.4.0 may be more\n backwards-incompatible than usual — please test when you upgrade.\n ","\n 1.3.3April 10, 2012DiffDocs
\n ","\n Many improvements to ",", which now provides the\n "," of the template function as a property, for potentially\n even more efficient pre-compilation on the server-side. You may now\n also set the "," option when creating a template,\n which will cause your passed-in data to be made available under the\n variable you named, instead of using a "," statement —\n significantly improving the speed of rendering the template.\n "," function, which allows you to filter an\n object literal with a list of allowed property names.\n "," function, for convenience when working\n with APIs that allow either functions or raw properties.\n "," function, because sometimes knowing that\n a value is a number just ain't quite enough.\n "," function may now also be passed the string name\n of a property to use as the sort order on each object.\n ","\n Fixed "," to work with sparse arrays.\n "," function now performs a shallow flatten\n instead of a deep one when computing array differences.\n ","\n parameter, which will cause the callback to fire on the leading\n instead of the trailing edge.\n ","\n 1.3.1January 23, 2012DiffDocs
\n "," function, as a safer way to use ","_.collect"," as an alias for ",". Smalltalkers, rejoice.\n ","\n Reverted an old change so that "," will correctly copy\n over keys with undefined values again.\n ","\n Bugfix to stop escaping slashes within interpolations in ","\n 1.3.0January 11, 2012DiffDocs
\n ","\n Removed AMD (RequireJS) support from Underscore. If you'd like to use\n Underscore with RequireJS, you can load it as a normal script, wrap\n or patch your copy, or download a forked version.\n ","\n 1.2.4January 4, 2012DiffDocs
\n ","\n You now can (and probably should, as it's simpler)\n write ","_.chain(list)","\n instead of ","_(list).chain()","\n Fix for escaped characters in Underscore templates, and for supporting\n customizations of "," that only define one or\n two of the required regexes.\n ","\n Fix for passing an array as the first argument to an ","_.wrap","'d function.\n ","\n Improved compatibility with ClojureScript, which adds a ","call","\n function to ","String.prototype","\n 1.2.3December 7, 2011DiffDocs
\n ","\n Dynamic scope is now preserved for compiled "," functions,\n so you can use the value of "," if you like.\n ","\n Sparse array support of ","\n Both ","_.reduceRight"," can now be passed an\n explicitly "," value. (There's no reason why you'd\n want to do this.)\n ","\n 1.2.2November 14, 2011DiffDocs
\n ","\n Continued tweaks to "," semantics. Now JS primitives are\n considered equivalent to their wrapped versions, and arrays are compared\n by their numeric properties only ","(#351)"," no longer tries to be smart about not double-escaping\n already-escaped HTML entities. Now it just escapes regardless ","(#350)","\n In ",", you may now leave semicolons out of evaluated\n statements if you wish: ","<% }) %>","(#369)","_.after(callback, 0)"," will now trigger the callback immediately,\n making \"after\" easier to use with asynchronous APIs ","(#366)","\n 1.2.1October 24, 2011DiffDocs
\n ","\n Several important bug fixes for ",", which should now\n do better on mutated Arrays, and on non-Array objects with\n "," properties. ","(#329)","\n James Burke\n contributed Underscore exporting for AMD module loaders, and\n Tony Lukasavage\n for Appcelerator Titanium.\n (#335, #338)\n ","\n You can now ","_.groupBy(list, 'property')"," as a shortcut for\n grouping values by a particular common property.\n ","'d functions now fire immediately upon invocation,\n and are rate-limited thereafter ","(#170, #266)","\n Most of the ","_.is[Type]"," checks no longer ducktype.\n "," function now also works on constructors, a-la\n ES5 ... but you would never want to use "," on a\n constructor function.\n ","_.clone"," no longer wraps non-object types in Objects.\n "," are now the preferred names for\n ","_.detect","_.select","\n 1.2.0October 5, 2011DiffDocs
\n "," function now\n supports true deep equality comparisons, with checks for cyclic structures,\n thanks to Kit Cambridge.\n ","\n Underscore templates now support HTML escaping interpolations, using\n ","<%- ... %>"," syntax.\n ","\n Ryan Tenney contributed ",", which uses a modified\n Fisher-Yates to give you a shuffled copy of an array.\n ","_.uniq"," can now be passed an optional iterator, to determine by\n what criteria an object should be considered unique.\n "," now takes an optional argument which will return the last\n N elements of the list.\n ","\n A new ","_.initial"," function was added, as a mirror of ","_.rest",",\n which returns all the initial values of a list (except the last N).\n ","1.1.7","July 13, 2011","\n Added ",", which aggregates a collection into groups of like items.\n Added ",", to complement the\n (re-named) ","_.intersection",".\n Various improvements for support of sparse arrays.\n ","_.toArray"," now returns a clone, if directly passed an array.\n ","_.functions"," now also returns the names of functions that are present\n in the prototype chain.\n ","1.1.6","April 18, 2011",", which will return a function that only runs after\n first being called a specified number of times.\n ","_.invoke"," can now take a direct function reference.\n ","_.every"," now requires an iterator function to be passed, which\n mirrors the ES5 API.\n "," no longer copies keys when the value is undefined.\n "," now errors when trying to bind an undefined value.\n ","1.1.5","March 20, 2011","\n Added an "," function, for use merging together JS objects\n representing default options.\n Added an ","_.once"," function, for manufacturing functions that should\n only ever execute a single time.\n "," now delegates to the native ES5 version,\n where available.\n "," now throws an error when used on non-Object values, as in\n ES5.\n Fixed a bug with "," when used over sparse arrays.\n ","1.1.4","January 9, 2011","\n Improved compliance with ES5's Array methods when passing ","\n as a value. "," now correctly sets "," for the\n wrapped function. "," now takes an optional flag for\n finding the insertion index in an array that is guaranteed to already\n be sorted. Avoiding the use of ",".callee",", to allow ","_.isArray","\n to work properly in ES5's strict mode.\n ","1.1.3","December 1, 2010","\n In CommonJS, Underscore may now be required with just: ","var _ = require(\"underscore\")",".\n Added "," functions.\n Removed ","_.breakLoop",", in favor of an ES5-style un-","break","-able\n each implementation — this removes the try/catch, and you'll now have\n better stack traces for exceptions that are thrown within an Underscore iterator.\n Improved the ","isType"," family of functions for better interoperability\n with Internet Explorer host objects.\n "," now correctly escapes backslashes in templates.\n Improved "," compatibility with the ES5 version:\n if you don't pass an initial value, the first item in the collection is used.\n "," no longer returns the iterated collection, for improved\n consistency with ES5's ","1.1.2","October 15, 2010","\n Fixed ",", which was mistakenly pointing at\n ","_.intersect","_.include",", like it should\n have been. Added ","_.unique","1.1.1","October 5, 2010","\n Improved the speed of ",", and its handling of multiline\n interpolations. Ryan Tenney contributed optimizations to many Underscore\n functions. An annotated version of the source code is now available.\n ","1.1.0","August 18, 2010","\n The method signature of "," has been changed to match\n the ES5 signature, instead of the Ruby/Prototype.js version.\n This is a backwards-incompatible change. "," may now be\n called with no arguments, and preserves whitespace. ","\n is a new alias for ","1.0.4","June 22, 2010","Andri Möll"," contributed the ","\n function, which can be used to speed up expensive repeated computations\n by caching the results.\n ","1.0.3","June 14, 2010","\n Patch that makes "," return "," if any property\n of the compared object has a "," value. Technically the correct\n thing to do, but of questionable semantics. Watch out for NaN comparisons.\n ","1.0.2","March 23, 2010","\n Fixes ","_.isArguments"," in recent versions of Opera, which have\n arguments objects as real Arrays.\n ","1.0.1","March 19, 2010","\n Bugfix for ",", when comparing two objects with the same\n number of undefined keys, but with different names.\n ","1.0.0","March 18, 2010","\n Things have been stable for many months now, so Underscore is now\n considered to be out of beta, at ","1.0",". Improvements since ","0.6","\n include ","_.isBoolean",", and the ability to have ","\n take multiple source objects.\n ","0.6.0","February 24, 2010","\n Major release. Incorporates a number of\n ","Mile Frawley's"," refactors for\n safer duck-typing on collection functions, and cleaner internals. A new\n ","_.mixin"," method that allows you to extend Underscore with utility\n functions of your own. Added ","_.times",", which works the same as in\n Ruby or Prototype.js. Native support for ES5's ","Array.isArray",",\n and ","\n 0.5.8January 28, 2010DiffDocs
\n Fixed Underscore's collection functions to work on\n NodeLists and\n HTMLCollections\n once more, thanks to\n Justin Tulloss.\n ","0.5.7","January 20, 2010","\n A safer implementation of ",", and a\n faster ","_.isNumber",",","thanks to\n ","Jed Schmidt","0.5.6","January 18, 2010","\n Customizable delimiters for ",", contributed by\n ","Noah Sloan","\n 0.5.5January 9, 2010DiffDocs
\n Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.\n ","0.5.4","January 5, 2010","\n Fix for multiple single quotes within a template string for\n ",". See:\n ","Rick Strahl's blog post","0.5.2","January 1, 2010","\n New implementations of ",", thanks to\n a suggestion from\n ","Robert Kieffer",".\n Instead of doing ","Object#toString","\n comparisons, they now check for expected properties, which is less safe,\n but more than an order of magnitude faster. Most other Underscore\n functions saw minor speed improvements as a result.\n ","Evgeniy Dolzhenko","\n contributed ","_.tap","similar to Ruby 1.9's",",\n which is handy for injecting side effects (like logging) into chained calls.\n ","0.5.1","December 9, 2009"," function. Lots of little safety checks\n and optimizations contributed by\n ","0.5.0","December 7, 2009","[API Changes]"," now takes the context object as\n its first parameter. If no method names are passed, all of the context\n object's methods are bound to it, enabling chaining and easier binding.\n "," now takes a single argument and returns the names\n of its Function properties. Calling ","_.functions(_)"," will get you\n the previous behavior.\n Added ","_.isRegExp"," so that "," can now test for RegExp equality.\n All of the \"is\" functions have been shrunk down into a single definition.\n ","Karl Guertin"," contributed patches.\n ","0.4.7","December 6, 2009",", for completeness.\n Optimizations for "," when checking equality between Arrays\n or Dates. "," is now ","25%–2X"," faster (depending on your\n browser) which speeds up the functions that rely on it, such as ","0.4.6","November 30, 2009","\n Added the "," function, a port of the\n ","Python\n function of the same name",", for generating flexibly-numbered lists\n of integers. Original patch contributed by\n ","Kirill Ishanov","0.4.5","November 19, 2009"," for Arrays and arguments objects, and aliased\n ","head","tail",",\n thanks to ","Luke Sutton","'s patches.\n Added tests ensuring that all Underscore Array functions also work on\n ","0.4.4","November 18, 2009",", for consistency. Fixed\n ","_.isEqual(NaN, NaN)"," (which is debatable).\n ","0.4.3","November 9, 2009","\n Started using the native ","StopIteration"," object in browsers that support it.\n Fixed Underscore setup for CommonJS environments.\n ","0.4.2","\n Renamed the unwrapping function to ",", for clarity.\n ","0.4.1","November 8, 2009","\n Chained Underscore objects now support the Array prototype methods, so\n that you can perform the full range of operations on a wrapped array\n without having to break your chain. Added a ","breakLoop"," method\n to "," in the middle of any Underscore iteration. Added an\n "," function that works on arrays and objects.\n ","0.4.0","November 7, 2009","\n All Underscore functions can now be called in an object-oriented style,\n like so: ","_([1, 2, 3]).map(...);",". Original patch provided by\n ","Marc-André Cournoyer",".\n Wrapped objects can be chained through multiple\n method invocations. A "," method\n was added, providing a sorted list of all the functions in Underscore.\n ","0.3.3","October 31, 2009","\n Added the JavaScript 1.8 function ",". Aliased it\n as ","foldr",", and aliased ","0.3.2","October 29, 2009","\n Now runs on stock ","Rhino","\n interpreters with: ","load(\"underscore.js\")"," as a utility function.\n ","0.3.1","\n All iterators are now passed in the original collection as their third\n argument, the same as JavaScript 1.6's ",". Iterating over\n objects is now called with ","(value, key, collection)",", for details\n see ","\n 0.3.0October 29, 2009DiffDocs
\n Added Dmitry Baranovskiy's\n comprehensive optimizations, merged in\n Kris Kowal's patches to make Underscore\n CommonJS and\n Narwhal compliant.\n ","0.2.0","October 28, 2009",", renamed "," to\n ",", added aliases for ","0.1.1",", so that the \"Underscore\" object can be assigned to\n other variables.\n ","\n 0.1.0October 28, 2009Docs
\n Initial release of Underscore.js.\n "]}

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?” … and the tie to go along with jQuery's tux and Backbone's suspenders.

Underscore provides over 100 functions that support both your favorite workaday functional helpers: map, filter, invoke — as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so on.

A complete Test Suite is included for your perusal.

You may also read through the annotated source code. There is a modular version with clickable import references as well.

You may choose between monolithic and modular imports. There is a quick summary of the options below, as well as a more comprehensive discussion in the article.

Enjoying Underscore, and want to turn it up to 11? Try Underscore-contrib.

The project is hosted on GitHub. You can report bugs and discuss features on the issues page or chat in the Gitter channel.

You can support the project by donating on Patreon. Enterprise coverage is available as part of the Tidelift Subscription.

Underscore is an open-source component of DocumentCloud.

v1.13.7 Downloads (Right-click, and use "Save As")

65.9 KB, Uncompressed with Plentiful Comments  (Source Map)
8.59 KB, Minified and Gzipped  (Source Map)
68.4 KB, Uncompressed with Bountiful Comments  (Source Map)
7.48 KB, Minified and Gzipped  (Source Map)
Unreleased, current master, use by your own judgement and at your own risk
Unreleased, current master, use if you’re feeling lucky

v1.13.7 CDN URLs (Use with <script src="..."></script>)

In most cases, you can replace the version number above by latest so that your embed will automatically use the latest version, or stable if you want to delay updating until an update has proven to be free of accidental breaking changes. Example:
https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js

Package Installation

If you are hardcoding the path to the file within the package and you are unsure which build to use, it is very likely that you need underscore-umd.js or the minified variant underscore-umd-min.js.

Monolithic Import (recommended)

Modular Import

For functions with multiple aliases, the file name of the module is always the first name that appears in the documentation. For example, _.reduce/_.inject/_.foldl is exported from underscore/modules/reduce.js. Modular usage is mostly recommended for creating a customized build of Underscore.

Engine Compatibility

Underscore 1.x is backwards compatible with any engine that fully supports ES3, while also utilizing newer features when available, such as Object.keys, typed arrays and ES modules. We routinely run our unittests against the JavaScript engines listed below:

In addition:

Underscore 2.x will likely remove support for some outdated environments.

Collection Functions (Arrays or Objects)

each_.each(list, iteratee, [context]) Alias: forEach source
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining.

_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, alert);
=> alerts each number value in turn...

Note: Collection functions work on arrays, objects, and array-like objects such as arguments, NodeList and similar. But it works by duck-typing, so avoid passing objects with a numeric length property. It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.

map_.map(list, iteratee, [context]) Alias: collect source
Produces a new array of values by mapping each value in list through a transformation function (iteratee). The iteratee is passed three arguments: the value, then the index (or key) of the iteration, and finally a reference to the entire list.

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
_.map([[1, 2], [3, 4]], _.first);
=> [1, 3]

reduce_.reduce(list, iteratee, [memo], [context]) Aliases: inject, foldl source
Also known as inject and foldl, reduce boils down a list of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iteratee. The iteratee is passed four arguments: the memo, then the value and index (or key) of the iteration, and finally a reference to the entire list.

If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.

var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6

reduceRight_.reduceRight(list, iteratee, [memo], [context]) Alias: foldr source
The right-associative version of reduce. Foldr is not as useful in JavaScript as it would be in a language with lazy evaluation.

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]

find_.find(list, predicate, [context]) Alias: detect source
Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list. predicate is transformed through iteratee to facilitate shorthand syntaxes.

var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2

filter_.filter(list, predicate, [context]) Alias: select source
Looks through each value in the list, returning an array of all the values that pass a truth test (predicate). predicate is transformed through iteratee to facilitate shorthand syntaxes.

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

findWhere_.findWhere(list, properties) source
Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});
=> {year: 1918, newsroom: "The New York Times",
  reason: "For its public service in publishing in full so many official reports,
  documents and speeches by European statesmen relating to the progress and
  conduct of the war."}

where_.where(list, properties) source
Looks through each value in the list, returning an array of all the values that matches the key-value pairs listed in properties.

_.where(listOfPlays, {author: "Shakespeare", year: 1611});
=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},
    {title: "The Tempest", author: "Shakespeare", year: 1611}]

reject_.reject(list, predicate, [context]) source
Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter. predicate is transformed through iteratee to facilitate shorthand syntaxes.

var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]

every_.every(list, [predicate], [context]) Alias: all source
Returns true if all of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a false element is found. predicate is transformed through iteratee to facilitate shorthand syntaxes.

_.every([2, 4, 5], function(num) { return num % 2 == 0; });
=> false

some_.some(list, [predicate], [context]) Alias: any source
Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found. predicate is transformed through iteratee to facilitate shorthand syntaxes.

_.some([null, 0, 'yes', false]);
=> true

contains_.contains(list, value, [fromIndex]) Aliases: include, includes source
Returns true if the value is present in the list. Uses indexOf internally, if list is an Array. Use fromIndex to start your search at a given index.

_.contains([1, 2, 3], 3);
=> true

invoke_.invoke(list, methodName, *arguments) source
Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation.

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
=> [[1, 5, 7], [1, 2, 3]]

pluck_.pluck(list, propertyName) source
A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

max_.max(list, [iteratee], [context]) source
Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required. This function can currently only compare numbers reliably. This function uses operator < (note).

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};

min_.min(list, [iteratee], [context]) source
Returns the minimum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. Infinity is returned if list is empty, so an isEmpty guard may be required. This function can currently only compare numbers reliably. This function uses operator < (note).

var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
=> 2

sortBy_.sortBy(list, iteratee, [context]) source
Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iteratee. iteratee may also be the string name of the property to sort by (eg. length). This function uses operator < (note).

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');
=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];

groupBy_.groupBy(list, iteratee, [context]) source
Splits a collection into sets, grouped by the result of running each value through iteratee. If iteratee is a string instead of a function, groups by the property named by iteratee on each of the values.

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}

_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}

indexBy_.indexBy(list, iteratee, [context]) source
Given a list, and an iteratee function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
=> {
  "40": {name: 'moe', age: 40},
  "50": {name: 'larry', age: 50},
  "60": {name: 'curly', age: 60}
}

countBy_.countBy(list, iteratee, [context]) source
Sorts a list into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.

_.countBy([1, 2, 3, 4, 5], function(num) {
  return num % 2 == 0 ? 'even': 'odd';
});
=> {odd: 3, even: 2}

shuffle_.shuffle(list) source
Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.

_.shuffle([1, 2, 3, 4, 5, 6]);
=> [4, 1, 6, 3, 5, 2]

sample_.sample(list, [n]) source
Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.

_.sample([1, 2, 3, 4, 5, 6]);
=> 4

_.sample([1, 2, 3, 4, 5, 6], 3);
=> [1, 6, 2]

toArray_.toArray(list) source
Creates a real Array from the list (anything that can be iterated over). Useful for transmuting the arguments object.

(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
=> [2, 3, 4]

size_.size(list) source
Return the number of values in the list.

_.size([1, 2, 3, 4, 5]);
=> 5

_.size({one: 1, two: 2, three: 3});
=> 3

partition_.partition(list, predicate) source
Split list into two arrays: one whose elements all satisfy predicate and one whose elements all do not satisfy predicate. predicate is transformed through iteratee to facilitate shorthand syntaxes.

_.partition([0, 1, 2, 3, 4, 5], isOdd);
=> [[1, 3, 5], [0, 2, 4]]

compact_.compact(list) source
Returns a copy of the list with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

_.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]

Array Functions

Note: All array functions will also work on the arguments object. However, Underscore functions are not designed to work on "sparse" arrays.

first_.first(array, [n]) Aliases: head, take source
Returns the first element of an array. Passing n will return the first n elements of the array.

_.first([5, 4, 3, 2, 1]);
=> 5

initial_.initial(array, [n]) source
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result.

_.initial([5, 4, 3, 2, 1]);
=> [5, 4, 3, 2]

last_.last(array, [n]) source
Returns the last element of an array. Passing n will return the last n elements of the array.

_.last([5, 4, 3, 2, 1]);
=> 1

rest_.rest(array, [index]) Aliases: tail, drop source
Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.

_.rest([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]

flatten_.flatten(array, [depth]) source
Flattens a nested array. If you pass true or 1 as the depth, the array will only be flattened a single level. Passing a greater number will cause the flattening to descend deeper into the nesting hierarchy. Omitting the depth argument, or passing false or Infinity, flattens the array all the way to the deepest nesting level.

_.flatten([1, [2], [3, [[4]]]]);
=> [1, 2, 3, 4];

_.flatten([1, [2], [3, [[4]]]], true);
=> [1, 2, 3, [[4]]];

_.flatten([1, [2], [3, [[4]]]], 2);
=> [1, 2, 3, [4]];

without_.without(array, *values) source
Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

union_.union(*arrays) source
Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

intersection_.intersection(*arrays) source
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

difference_.difference(array, *others) source
Similar to without, but returns the values from array that are not present in the other arrays.

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique source
Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurrence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.

_.uniq([1, 2, 1, 4, 1, 3]);
=> [1, 2, 4, 3]

zip_.zip(*arrays) source
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

unzip_.unzip(array) Alias: transpose source
The opposite of zip. Given an array of arrays, returns a series of new arrays, the first of which contains all of the first elements in the input arrays, the second of which contains all of the second elements, and so on. If you're working with a matrix of nested arrays, this can be used to transpose the matrix.

_.unzip([["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]);
=> [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]]

object_.object(list, [values]) source
Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. Passing by pairs is the reverse of pairs. If duplicate keys exist, the last value wins.

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}

_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
=> {moe: 30, larry: 40, curly: 50}

chunk_.chunk(array, length) source
Chunks an array into multiple arrays, each containing length or fewer items.

var partners = _.chunk(_.shuffle(kindergarten), 2);
=> [["Tyrone", "Elie"], ["Aidan", "Sam"], ["Katrina", "Billie"], ["Little Timmy"]]

indexOf_.indexOf(array, value, [isSorted]) source
Returns the index at which value can be found in the array, or -1 if value is not present in the array. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search ... or, pass a number as the third argument in order to look for the first matching value in the array after the given index. If isSorted is true, this function uses operator < (note).

_.indexOf([1, 2, 3], 2);
=> 1

lastIndexOf_.lastIndexOf(array, value, [fromIndex]) source
Returns the index of the last occurrence of value in the array, or -1 if value is not present. Pass fromIndex to start your search at a given index.

_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
=> 4

sortedIndex_.sortedIndex(array, value, [iteratee], [context]) source
Uses a binary search to determine the smallest index at which the value should be inserted into the array in order to maintain the array's sorted order. If an iteratee function is provided, it will be used to compute the sort ranking of each value, including the value you pass. The iteratee may also be the string name of the property to sort by (eg. length). This function uses operator < (note).

_.sortedIndex([10, 20, 30, 40, 50], 35);
=> 3

var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];
_.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');
=> 1

findIndex_.findIndex(array, predicate, [context]) source
Similar to _.indexOf, returns the first index where the predicate truth test passes; otherwise returns -1.

_.findIndex([4, 6, 8, 12], isPrime);
=> -1 // not found
_.findIndex([4, 6, 7, 12], isPrime);
=> 2

findLastIndex_.findLastIndex(array, predicate, [context]) source
Like _.findIndex but iterates the array in reverse, returning the index closest to the end where the predicate truth test passes.

var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},
             {'id': 2, 'name': 'Ted', 'last': 'White'},
             {'id': 3, 'name': 'Frank', 'last': 'James'},
             {'id': 4, 'name': 'Ted', 'last': 'Jones'}];
_.findLastIndex(users, {
  name: 'Ted'
});
=> 3

range_.range([start], stop, [step]) source
A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1 if start is before stop, otherwise -1. Returns a list of integers from start (inclusive) to stop (exclusive), incremented (or decremented) by step.

_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0);
=> []

Function (uh, ahem) Functions

bind_.bind(function, object, *arguments) source
Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, pass arguments to the function to pre-fill them, also known as partial application. For partial application without context binding, use partial.

var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name: 'moe'}, 'hi');
func();
=> 'hi: moe'

bindAll_.bindAll(object, *methodNames) source
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. methodNames are required.

var buttonView = {
  label  : 'underscore',
  onClick: function(){ alert('clicked: ' + this.label); },
  onHover: function(){ console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView, 'onClick', 'onHover');
// When the button is clicked, this.label will have the correct value.
jQuery('#underscore_button').on('click', buttonView.onClick);

partial_.partial(function, *arguments) source
Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be pre-filled, but left open to supply at call-time. Note: if you need _ placeholders and a this binding at the same time, use both _.partial and _.bind.

var subtract = function(a, b) { return b - a; };
sub5 = _.partial(subtract, 5);
sub5(20);
=> 15

// Using a placeholder
subFrom20 = _.partial(subtract, _, 20);
subFrom20(5);
=> 15

memoize_.memoize(function, [hashFunction]) source
Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default hashFunction just uses the first argument to the memoized function as the key. The cache of memoized values is available as the cache property on the returned function.

var fibonacci = _.memoize(function(n) {
  return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});

delay_.delay(function, wait, *arguments) source
Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
=> 'logged later' // Appears after one second.

defer_.defer(function, *arguments) source
Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

_.defer(function(){ alert('deferred'); });
// Returns from the function before the alert runs.

throttle_.throttle(function, wait, [options]) source
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

By default, throttle will execute the function as soon as you call it for the first time, and, if you call it again any number of times during the wait period, as soon as that period is over. If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable the execution on the trailing-edge, pass
{trailing: false}.

var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

If you need to cancel a scheduled throttle, you can call .cancel() on the throttled function.

debounce_.debounce(function, wait, [immediate]) source
Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

At the end of the wait interval, the function will be called with the arguments that were passed most recently to the debounced function.

Pass true for the immediate argument to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time.

var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);

If you need to cancel a scheduled debounce, you can call .cancel() on the debounced function.

once_.once(function) source
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.

after_.after(count, function) source
Creates a wrapper of function that does nothing at first. From the count-th call onwards, it starts actually calling function. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

var renderNotes = _.after(notes.length, render);
_.each(notes, function(note) {
  note.asyncSave({success: renderNotes});
});
// renderNotes is run once, after all notes have saved.

before_.before(count, function) source
Creates a wrapper of function that memoizes its return value. From the count-th call onwards, the memoized result of the last invocation is returned immediately instead of invoking function again. So the wrapper will invoke function at most count - 1 times.

var monthlyMeeting = _.before(3, askForRaise);
monthlyMeeting();
monthlyMeeting();
monthlyMeeting();
// the result of any subsequent calls is the same as the second call

wrap_.wrap(function, wrapper) source
Wraps the first function inside of the wrapper function, passing it as the first argument. This allows the wrapper to execute code before and after the function runs, adjust the arguments, and execute it conditionally.

var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func) {
  return "before, " + func("moe") + ", after";
});
hello();
=> 'before, hello: moe, after'

negate_.negate(predicate) source
Returns a new negated version of the predicate function.

var isFalsy = _.negate(Boolean);
_.find([-2, -1, 0, 1, 2], isFalsy);
=> 0

compose_.compose(*functions) source
Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

var greet    = function(name){ return "hi: " + name; };
var exclaim  = function(statement){ return statement.toUpperCase() + "!"; };
var welcome = _.compose(greet, exclaim);
welcome('moe');
=> 'hi: MOE!'

restArguments_.restArguments(function, [startIndex]) source
Returns a version of the function that, when called, receives all arguments from and beyond startIndex collected into a single array. If you don’t pass an explicit startIndex, it will be determined by looking at the number of arguments to the function itself. Similar to ES6’s rest parameters syntax.

var raceResults = _.restArguments(function(gold, silver, bronze, everyoneElse) {
  _.each(everyoneElse, sendConsolations);
});

raceResults("Dopey", "Grumpy", "Happy", "Sneezy", "Bashful", "Sleepy", "Doc");

Object Functions

keys_.keys(object) source
Retrieve all the names of the object's own enumerable properties.

_.keys({one: 1, two: 2, three: 3});
=> ["one", "two", "three"]

allKeys_.allKeys(object) source
Retrieve all the names of object's own and inherited properties.

function Stooge(name) {
  this.name = name;
}
Stooge.prototype.silly = true;
_.allKeys(new Stooge("Moe"));
=> ["name", "silly"]

values_.values(object) source
Return all of the values of the object's own properties.

_.values({one: 1, two: 2, three: 3});
=> [1, 2, 3]

mapObject_.mapObject(object, iteratee, [context]) source
Like map, but for objects. Transform the value of each property in turn.

_.mapObject({start: 5, end: 12}, function(val, key) {
  return val + 5;
});
=> {start: 10, end: 17}

pairs_.pairs(object) source
Convert an object into a list of [key, value] pairs. The opposite of object.

_.pairs({one: 1, two: 2, three: 3});
=> [["one", 1], ["two", 2], ["three", 3]]

invert_.invert(object) source
Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

_.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"});
=> {Moses: "Moe", Louis: "Larry", Jerome: "Curly"};

create_.create(prototype, props) source
Creates a new object with the given prototype, optionally attaching props as own properties. Basically, Object.create, but without all of the property descriptor jazz.

var moe = _.create(Stooge.prototype, {name: "Moe"});

functions_.functions(object) Alias: methods source
Returns a sorted list of the names of every method in an object — that is to say, the name of every function property of the object.

_.functions(_);
=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...

findKey_.findKey(object, predicate, [context]) source
Similar to _.findIndex but for keys in objects. Returns the key where the predicate truth test passes or undefined. predicate is transformed through iteratee to facilitate shorthand syntaxes.

extend_.extend(destination, *sources) source
Shallowly copy all of the properties in the source objects over to the destination object, and return the destination object. Any nested objects or arrays will be copied by reference, not duplicated. It's in-order, so the last source will override properties of the same name in previous arguments.

_.extend({name: 'moe'}, {age: 50});
=> {name: 'moe', age: 50}

extendOwn_.extendOwn(destination, *sources) Alias: assign source
Like extend, but only copies own properties over to the destination object.

pick_.pick(object, *keys) source
Return a copy of the object, filtered to only have values for the allowed keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {age: 50}

omit_.omit(object, *keys) source
Return a copy of the object, filtered to omit the disallowed keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
=> {name: 'moe', age: 50}
_.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {name: 'moe', userid: 'moe1'}

defaults_.defaults(object, *defaults) source
Returns object after filling in its undefined properties with the first value present in the following list of defaults objects.

var iceCream = {flavor: "chocolate"};
_.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});
=> {flavor: "chocolate", sprinkles: "lots"}

clone_.clone(object) source
Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.

_.clone({name: 'moe'});
=> {name: 'moe'};

tap_.tap(object, interceptor) source
Invokes interceptor with the object, and then returns object. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.

_.chain([1,2,3,200])
  .filter(function(num) { return num % 2 == 0; })
  .tap(alert)
  .map(function(num) { return num * num })
  .value();
=> // [2, 200] (alerted)
=> [4, 40000]

toPath_.toPath(path) source
Ensures that path is an array. If path is a string, it is wrapped in a single-element array; if it is an array already, it is returned unmodified.

_.toPath('key');
=> ['key']
_.toPath(['a', 0, 'b']);
=> ['a', 0, 'b'] // (same array)

_.toPath is used internally in has, get, invoke, property, propertyOf and result, as well as in iteratee and all functions that depend on it, in order to normalize deep property paths. You can override _.toPath if you want to customize this behavior, for example to enable Lodash-like string path shorthands. Be advised that altering _.toPath will unavoidably cause some keys to become unreachable; override at your own risk.

// Support dotted path shorthands.
var originalToPath = _.toPath;
_.mixin({
  toPath: function(path) {
    return _.isString(path) ? path.split('.') : originalToPath(path);
  }
});
_.get({a: [{b: 5}]}, 'a.0.b');
=> 5

get_.get(object, path, [default]) source
Returns the specified property of object. path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching. If the property does not exist or is undefined, the optional default is returned.

_.get({a: 10}, 'a');
=> 10
_.get({a: [{b: 2}]}, ['a', 0, 'b']);
=> 2
_.get({a: 10}, 'b', 100);
=> 100

has_.has(object, key) source
Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.

_.has({a: 1, b: 2, c: 3}, "b");
=> true

property_.property(path) source
Returns a function that will return the specified property of any passed-in object. path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching.

var stooge = {name: 'moe'};
'moe' === _.property('name')(stooge);
=> true

var stooges = {moe: {fears: {worst: 'Spiders'}}, curly: {fears: {worst: 'Moe'}}};
var curlysWorstFear = _.property(['curly', 'fears', 'worst']);
curlysWorstFear(stooges);
=> 'Moe'

propertyOf_.propertyOf(object) source
Inverse of _.property. Takes an object and returns a function which will return the value of a provided property.

var stooge = {name: 'moe'};
_.propertyOf(stooge)('name');
=> 'moe'

matcher_.matcher(attrs) Alias: matches source
Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs.

var ready = _.matcher({selected: true, visible: true});
var readyToGoList = _.filter(list, ready);

isEqual_.isEqual(object, other) source
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone  = {name: 'moe', luckyNumbers: [13, 27, 34]};
stooge == clone;
=> false
_.isEqual(stooge, clone);
=> true

isMatch_.isMatch(object, properties) source
Tells you if the keys and values in properties are contained in object.

var stooge = {name: 'moe', age: 32};
_.isMatch(stooge, {age: 32});
=> true

isEmpty_.isEmpty(collection) source
Returns true if collection has no elements. For strings and array-like objects _.isEmpty checks if the length property is 0. For other objects, it returns true if the object has no enumerable own-properties. Note that primitive numbers, booleans and symbols are always empty by this definition.

_.isEmpty([1, 2, 3]);
=> false
_.isEmpty({});
=> true

isElement_.isElement(object) source
Returns true if object is a DOM element.

_.isElement(jQuery('body')[0]);
=> true

isArray_.isArray(object) source
Returns true if object is an Array.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true

isObject_.isObject(value) source
Returns true if value is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings and numbers are not.

_.isObject({});
=> true
_.isObject(1);
=> false

isArguments_.isArguments(object) source
Returns true if object is an Arguments object.

(function(){ return _.isArguments(arguments); })(1, 2, 3);
=> true
_.isArguments([1,2,3]);
=> false

isFunction_.isFunction(object) source
Returns true if object is a Function.

_.isFunction(alert);
=> true

isString_.isString(object) source
Returns true if object is a String.

_.isString("moe");
=> true

isNumber_.isNumber(object) source
Returns true if object is a Number (including NaN).

_.isNumber(8.4 * 5);
=> true

isFinite_.isFinite(object) source
Returns true if object is a finite Number.

_.isFinite(-101);
=> true

_.isFinite(-Infinity);
=> false

isBoolean_.isBoolean(object) source
Returns true if object is either true or false.

_.isBoolean(null);
=> false

isDate_.isDate(object) source
Returns true if object is a Date.

_.isDate(new Date());
=> true

isRegExp_.isRegExp(object) source
Returns true if object is a RegExp.

_.isRegExp(/moe/);
=> true

isError_.isError(object) source
Returns true if object inherits from an Error.

try {
  throw new TypeError("Example");
} catch (o_O) {
  _.isError(o_O);
}
=> true

isSymbol_.isSymbol(object) source
Returns true if object is a Symbol.

_.isSymbol(Symbol());
=> true

isMap_.isMap(object) source
Returns true if object is a Map.

_.isMap(new Map());
=> true

isWeakMap_.isWeakMap(object) source
Returns true if object is a WeakMap.

_.isWeakMap(new WeakMap());
=> true

isSet_.isSet(object) source
Returns true if object is a Set.

_.isSet(new Set());
=> true

isWeakSet_.isWeakSet(object) source
Returns true if object is a WeakSet.

_.isWeakSet(WeakSet());
=> true

isArrayBuffer_.isArrayBuffer(object) source
Returns true if object is an ArrayBuffer.

_.isArrayBuffer(new ArrayBuffer(8));
=> true

isDataView_.isDataView(object) source
Returns true if object is a DataView.

_.isDataView(new DataView(new ArrayBuffer(8)));
=> true

isTypedArray_.isTypedArray(object) source
Returns true if object is a TypedArray.

_.isTypedArray(new Int8Array(8));
=> true

isNaN_.isNaN(object) source
Returns true if object is NaN.
Note: this is not the same as the native isNaN function, which will also return true for many other not-number values, such as undefined.

_.isNaN(NaN);
=> true
isNaN(undefined);
=> true
_.isNaN(undefined);
=> false

isNull_.isNull(object) source
Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false

isUndefined_.isUndefined(value) source
Returns true if value is undefined.

_.isUndefined(window.missingVariable);
=> true

Utility Functions

noConflict_.noConflict() source
Give control of the global _ variable back to its previous owner. Returns a reference to the Underscore object.

var underscore = _.noConflict();

The _.noConflict function is not present if you use the EcmaScript 6, AMD or CommonJS module system to import Underscore.

identity_.identity(value) source
Returns the same value that is used as the argument. In math: f(x) = x
This function looks useless, but is used throughout Underscore as a default iteratee.

var stooge = {name: 'moe'};
stooge === _.identity(stooge);
=> true

constant_.constant(value) source
Creates a function that returns the same value that is used as the argument of _.constant.

var stooge = {name: 'moe'};
stooge === _.constant(stooge)();
=> true

noop_.noop() source
Returns undefined irrespective of the arguments passed to it. Useful as the default for optional callback arguments.

obj.initialize = _.noop;

times_.times(n, iteratee, [context]) source
Invokes the given iteratee function n times. Each invocation of iteratee is called with an index argument. Produces an array of the returned values.

_.times(3, function(n){ genie.grantWishNumber(n); });

random_.random(min, max) source
Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number.

_.random(0, 100);
=> 42

mixin_.mixin(object) source
Allows you to extend Underscore with your own utility functions. Pass a hash of {name: function} definitions to have your functions added to the Underscore object, as well as the OOP wrapper. Returns the Underscore object to facilitate chaining.

_.mixin({
  capitalize: function(string) {
    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  }
});
_("fabio").capitalize();
=> "Fabio"

iteratee_.iteratee(value, [context]) source
Generates a callback that can be applied to each element in a collection. _.iteratee supports a number of shorthand syntaxes for common callback use cases. Depending upon value's type, _.iteratee will return:

// No value
_.iteratee();
=> _.identity()

// Function
_.iteratee(function(n) { return n * 2; });
=> function(n) { return n * 2; }

// Object
_.iteratee({firstName: 'Chelsea'});
=> _.matcher({firstName: 'Chelsea'});

// Anything else
_.iteratee('firstName');
=> _.property('firstName');

The following Underscore methods transform their predicates through _.iteratee: countBy, every, filter, find, findIndex, findKey, findLastIndex, groupBy, indexBy, map, mapObject, max, min, partition, reject, some, sortBy, sortedIndex, and uniq

You may overwrite _.iteratee with your own custom function, if you want additional or different shorthand syntaxes:

// Support `RegExp` predicate shorthand.
var builtinIteratee = _.iteratee;
_.iteratee = function(value, context) {
  if (_.isRegExp(value)) return function(obj) { return value.test(obj) };
  return builtinIteratee(value, context);
};

uniqueId_.uniqueId([prefix]) source
Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.

_.uniqueId('contact_');
=> 'contact_104'

escape_.escape(string) source
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.

_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"

unescape_.unescape(string) source
The opposite of escape, replaces &amp;, &lt;, &gt;, &quot;, &#x60; and &#x27; with their unescaped counterparts.

_.unescape('Curly, Larry &amp; Moe');
=> "Curly, Larry & Moe"

result_.result(object, property, [defaultValue]) source
If the value of the named property is a function then invoke it with the object as context; otherwise, return it. If a default value is provided and the property doesn't exist or is undefined then the default will be returned. If defaultValue is a function its result will be returned.

var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
_.result(object, 'meat', 'ham');
=> "ham"

now_.now() source
Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions.

_.now();
=> 1392066795351

template_.template(templateString, [settings]) source
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate values, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>. When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables. The settings argument should be a hash containing any _.templateSettings that should be overridden.

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

var template = _.template("<b><%- value %></b>");
template({value: '<script>'});
=> "<b>&lt;script&gt;</b>"

You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge"

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML-escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string. Note that if part of your template matches more than one of these regexes, the first will be applied by the following order of priority: (1) escape, (2) interpolate, (3) evaluate. You may define or omit any combination of the three. For example, to perform Mustache.js-style templating:

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name: "Mustache"});
=> "Hello Mustache!"

By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.

_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
=> "Using 'with': no"

Precompiling your templates can be a big help when debugging errors you can't reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. The source property is available on the compiled template function for easy precompilation.

<script>
  JST.project = <%= _.template(jstText).source %>;
</script>

Object-Oriented Style

You can use Underscore in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers. source, source

_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });

Chaining

Calling chain will cause all future method calls to return wrapped objects. When you've finished the computation, call value to retrieve the final value. Here's an example of chaining together a map/flatten/reduce, in order to get the word count of every word in a song.

var lyrics = [
  {line: 1, words: "I'm a lumberjack and I'm okay"},
  {line: 2, words: "I sleep all night and I work all day"},
  {line: 3, words: "He's a lumberjack and he's okay"},
  {line: 4, words: "He sleeps all night and he works all day"}
];

_.chain(lyrics)
  .map(function(line) { return line.words.split(' '); })
  .flatten()
  .reduce(function(counts, word) {
    counts[word] = (counts[word] || 0) + 1;
    return counts;
  }, {})
  .value();

=> {lumberjack: 2, all: 4, night: 2 ... }

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

chain_.chain(obj) source
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
var youngest = _.chain(stooges)
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  .first()
  .value();
=> "moe is 21"

value_.chain(obj).value() source
Extracts the value of a wrapped object.

_.chain([1, 2, 3]).reverse().value();
=> [3, 2, 1]

Underscore.lua, a Lua port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Dollar.swift, a Swift port of many of the Underscore.js functions and more. (source)

Underscore.m, an Objective-C port of many of the Underscore.js functions, using a syntax that encourages chaining. (source)

_.m, an alternative Objective-C port that tries to stick a little closer to the original Underscore.js API. (source)

Underscore.php, a PHP port of the functions that are applicable in both languages. Tailored for PHP 5.4 and made with data-type tolerance in mind. (source)

Underscore-perl, a Perl port of many of the Underscore.js functions, aimed at on Perl hashes and arrays. (source)

Underscore.cfc, a Coldfusion port of many of the Underscore.js functions. (source)

Underscore.string, an Underscore extension that adds functions for string-manipulation: trim, startsWith, contains, capitalize, reverse, sprintf, and more.

Underscore-java, a java port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Ruby's Enumerable module.

Prototype.js, which provides JavaScript with collection functions in the manner closest to Ruby's Enumerable.

Oliver Steele's Functional JavaScript, which includes comprehensive higher-order function support as well as string lambdas.

Michael Aufreiter's Data.js, a data manipulation + persistence library for JavaScript.

Python's itertools.

PyToolz, a Python port that extends itertools and functools to include much of the Underscore API.

Funcy, a practical collection of functional helpers for Python, partially inspired by Underscore.

Notes

On the use of < in Underscore
Underscore functions that depend on ordering, such as _.sortBy and _.sortedIndex, use JavaScript’s built-in relational operators, specifically the “less than” operator <. It is important to understand that these operators are only meaningful for numbers and strings. You can throw any value to them, but JavaScript will convert the operands to string or number first before performing the actual comparison. If you pass an operand that cannot be meaningfully converted to string or number, it ends up being NaN by default. This value is unsortable.

Ideally, the values that you are sorting should either be all (meaningfully convertible to) strings or all (meaningfully convertible to) numbers. If this is not the case, you have two options:

Change Log

1.13.7July 24, 2024DiffDocs

1.13.6September 24, 2022DiffDocs
Hotfix for version 1.13.5 to remove a postinstall script from the package.json, which unexpectedly broke many people's builds.

1.13.5September 23, 2022DiffDocs

1.13.4June 2, 2022DiffDocs

1.13.3April 23, 2022DiffDocs

1.13.2December 16, 2021DiffDocs

1.13.1April 15, 2021DiffDocs

1.13.0April 9, 2021DiffDocs

1.13.0-3March 31, 2021DiffDocs

1.13.0-2March 15, 2021DiffDocs

1.12.1March 15, 2021DiffDocs

1.13.0-1March 11, 2021DiffDocs

1.13.0-0March 9, 2021DiffDocs

1.12.0November 24, 2020DiffDocs

1.11.0August 28, 2020DiffDocsArticle

1.10.2March 30, 2020DiffDocs

1.10.1March 30, 2020DiffDocs

1.10.0March 30, 2020DiffDocs

1.9.2Jan 6, 2020DiffDocs

1.9.1May 31, 2018DiffDocs

1.9.0April 18, 2018DiffDocs

1.8.3April 2, 2015DiffDocs

1.8.2Feb. 22, 2015DiffDocs

1.8.1Feb. 19, 2015DiffDocs

1.8.0Feb. 19, 2015DiffDocs

1.7.0August 26, 2014DiffDocs

1.6.0February 10, 2014DiffDocs

1.5.2September 7, 2013DiffDocs

1.5.1July 8, 2013DiffDocs

1.5.0July 6, 2013DiffDocs

1.4.4January 30, 2013DiffDocs

1.4.3December 4, 2012DiffDocs

1.4.2October 6, 2012DiffDocs

1.4.1October 1, 2012DiffDocs

1.4.0September 27, 2012DiffDocs

1.3.3April 10, 2012DiffDocs

1.3.1January 23, 2012DiffDocs

1.3.0January 11, 2012DiffDocs

1.2.4January 4, 2012DiffDocs

1.2.3December 7, 2011DiffDocs

1.2.2November 14, 2011DiffDocs

1.2.1October 24, 2011DiffDocs

1.2.0October 5, 2011DiffDocs

1.1.7July 13, 2011DiffDocs
Added _.groupBy, which aggregates a collection into groups of like items. Added _.union and _.difference, to complement the (re-named) _.intersection. Various improvements for support of sparse arrays. _.toArray now returns a clone, if directly passed an array. _.functions now also returns the names of functions that are present in the prototype chain.

1.1.6April 18, 2011DiffDocs
Added _.after, which will return a function that only runs after first being called a specified number of times. _.invoke can now take a direct function reference. _.every now requires an iterator function to be passed, which mirrors the ES5 API. _.extend no longer copies keys when the value is undefined. _.bind now errors when trying to bind an undefined value.

1.1.5March 20, 2011DiffDocs
Added an _.defaults function, for use merging together JS objects representing default options. Added an _.once function, for manufacturing functions that should only ever execute a single time. _.bind now delegates to the native ES5 version, where available. _.keys now throws an error when used on non-Object values, as in ES5. Fixed a bug with _.keys when used over sparse arrays.

1.1.4January 9, 2011DiffDocs
Improved compliance with ES5's Array methods when passing null as a value. _.wrap now correctly sets this for the wrapped function. _.indexOf now takes an optional flag for finding the insertion index in an array that is guaranteed to already be sorted. Avoiding the use of .callee, to allow _.isArray to work properly in ES5's strict mode.

1.1.3December 1, 2010DiffDocs
In CommonJS, Underscore may now be required with just:
var _ = require("underscore"). Added _.throttle and _.debounce functions. Removed _.breakLoop, in favor of an ES5-style un-break-able each implementation — this removes the try/catch, and you'll now have better stack traces for exceptions that are thrown within an Underscore iterator. Improved the isType family of functions for better interoperability with Internet Explorer host objects. _.template now correctly escapes backslashes in templates. Improved _.reduce compatibility with the ES5 version: if you don't pass an initial value, the first item in the collection is used. _.each no longer returns the iterated collection, for improved consistency with ES5's forEach.

1.1.2October 15, 2010DiffDocs
Fixed _.contains, which was mistakenly pointing at _.intersect instead of _.include, like it should have been. Added _.unique as an alias for _.uniq.

1.1.1October 5, 2010DiffDocs
Improved the speed of _.template, and its handling of multiline interpolations. Ryan Tenney contributed optimizations to many Underscore functions. An annotated version of the source code is now available.

1.1.0August 18, 2010DiffDocs
The method signature of _.reduce has been changed to match the ES5 signature, instead of the Ruby/Prototype.js version. This is a backwards-incompatible change. _.template may now be called with no arguments, and preserves whitespace. _.contains is a new alias for _.include.

1.0.4June 22, 2010DiffDocs
Andri Möll contributed the _.memoize function, which can be used to speed up expensive repeated computations by caching the results.

1.0.3June 14, 2010DiffDocs
Patch that makes _.isEqual return false if any property of the compared object has a NaN value. Technically the correct thing to do, but of questionable semantics. Watch out for NaN comparisons.

1.0.2March 23, 2010DiffDocs
Fixes _.isArguments in recent versions of Opera, which have arguments objects as real Arrays.

1.0.1March 19, 2010DiffDocs
Bugfix for _.isEqual, when comparing two objects with the same number of undefined keys, but with different names.

1.0.0March 18, 2010DiffDocs
Things have been stable for many months now, so Underscore is now considered to be out of beta, at 1.0. Improvements since 0.6 include _.isBoolean, and the ability to have _.extend take multiple source objects.

0.6.0February 24, 2010DiffDocs
Major release. Incorporates a number of Mile Frawley's refactors for safer duck-typing on collection functions, and cleaner internals. A new _.mixin method that allows you to extend Underscore with utility functions of your own. Added _.times, which works the same as in Ruby or Prototype.js. Native support for ES5's Array.isArray, and Object.keys.

0.5.8January 28, 2010DiffDocs
Fixed Underscore's collection functions to work on NodeLists and HTMLCollections once more, thanks to Justin Tulloss.

0.5.7January 20, 2010DiffDocs
A safer implementation of _.isArguments, and a faster _.isNumber,
thanks to Jed Schmidt.

0.5.6January 18, 2010DiffDocs
Customizable delimiters for _.template, contributed by Noah Sloan.

0.5.5January 9, 2010DiffDocs
Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.

0.5.4January 5, 2010DiffDocs
Fix for multiple single quotes within a template string for _.template. See: Rick Strahl's blog post.

0.5.2January 1, 2010DiffDocs
New implementations of isArray, isDate, isFunction, isNumber, isRegExp, and isString, thanks to a suggestion from Robert Kieffer. Instead of doing Object#toString comparisons, they now check for expected properties, which is less safe, but more than an order of magnitude faster. Most other Underscore functions saw minor speed improvements as a result. Evgeniy Dolzhenko contributed _.tap, similar to Ruby 1.9's, which is handy for injecting side effects (like logging) into chained calls.

0.5.1December 9, 2009DiffDocs
Added an _.isArguments function. Lots of little safety checks and optimizations contributed by Noah Sloan and Andri Möll.

0.5.0December 7, 2009DiffDocs
[API Changes] _.bindAll now takes the context object as its first parameter. If no method names are passed, all of the context object's methods are bound to it, enabling chaining and easier binding. _.functions now takes a single argument and returns the names of its Function properties. Calling _.functions(_) will get you the previous behavior. Added _.isRegExp so that isEqual can now test for RegExp equality. All of the "is" functions have been shrunk down into a single definition. Karl Guertin contributed patches.

0.4.7December 6, 2009DiffDocs
Added isDate, isNaN, and isNull, for completeness. Optimizations for isEqual when checking equality between Arrays or Dates. _.keys is now 25%–2X faster (depending on your browser) which speeds up the functions that rely on it, such as _.each.

0.4.6November 30, 2009DiffDocs
Added the range function, a port of the Python function of the same name, for generating flexibly-numbered lists of integers. Original patch contributed by Kirill Ishanov.

0.4.5November 19, 2009DiffDocs
Added rest for Arrays and arguments objects, and aliased first as head, and rest as tail, thanks to Luke Sutton's patches. Added tests ensuring that all Underscore Array functions also work on arguments objects.

0.4.4November 18, 2009DiffDocs
Added isString, and isNumber, for consistency. Fixed _.isEqual(NaN, NaN) to return true (which is debatable).

0.4.3November 9, 2009DiffDocs
Started using the native StopIteration object in browsers that support it. Fixed Underscore setup for CommonJS environments.

0.4.2November 9, 2009DiffDocs
Renamed the unwrapping function to value, for clarity.

0.4.1November 8, 2009DiffDocs
Chained Underscore objects now support the Array prototype methods, so that you can perform the full range of operations on a wrapped array without having to break your chain. Added a breakLoop method to break in the middle of any Underscore iteration. Added an isEmpty function that works on arrays and objects.

0.4.0November 7, 2009DiffDocs
All Underscore functions can now be called in an object-oriented style, like so: _([1, 2, 3]).map(...);. Original patch provided by Marc-André Cournoyer. Wrapped objects can be chained through multiple method invocations. A functions method was added, providing a sorted list of all the functions in Underscore.

0.3.3October 31, 2009DiffDocs
Added the JavaScript 1.8 function reduceRight. Aliased it as foldr, and aliased reduce as foldl.

0.3.2October 29, 2009DiffDocs
Now runs on stock Rhino interpreters with: load("underscore.js"). Added identity as a utility function.

0.3.1October 29, 2009DiffDocs
All iterators are now passed in the original collection as their third argument, the same as JavaScript 1.6's forEach. Iterating over objects is now called with (value, key, collection), for details see _.each.

0.3.0October 29, 2009DiffDocs
Added Dmitry Baranovskiy's comprehensive optimizations, merged in Kris Kowal's patches to make Underscore CommonJS and Narwhal compliant.

0.2.0October 28, 2009DiffDocs
Added compose and lastIndexOf, renamed inject to reduce, added aliases for inject, filter, every, some, and forEach.

0.1.1October 28, 2009DiffDocs
Added noConflict, so that the "Underscore" object can be assigned to other variables.

0.1.0October 28, 2009Docs
Initial release of Underscore.js.

A DocumentCloud Project