underscore-min.js
file UMD available. After that include the following CDN link inside your code in order to run the underscore.js code inside the browser.
Node.js
and npm installed.npm install underscore
yarn
yarn install underscore
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script type="text/javascript">
var numbers = [100, 50, 400, 66, 999];
console.log(_.max(numbers));
</script>
</body>
</html>
Output :
_.max() function
is used to find the minimum element from the list passed. If an iteratee is given, then it will be applied to each value and generate criteria to rank the values and find the minimum element._.max(list, [iteratee], [context])
._max()
function takes the element from the list one by one and do compares the elements to find the maximum number in the list. After traversing and comparing all the elements, the _.max()
function ends.<html>
<head>
<script type="text/javascript" src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
var numbers = [100, 50, 400, 66, 999];
console.log(_.max(numbers));
</script>
</body>
</html>
Output :
_.each(list, iteratee, [context])
Alias: forEach_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, alert);
=> alerts each number value in turn...
_.map(list, iteratee, [context])
Alias: collect_.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(list, iteratee, [memo], [context])
Aliases : inject, foldlvar sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6
_.reduceRight(list, iteratee, [memo], [context])
Alias : foldrvar 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(list, predicate, [context])
Alias : detectvar even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2
_.filter(list, predicate, [context])
Alias : selectvar evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
_.findWhere(list, properties)
_.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(list, properties)
_.where(listOfPlays, {author: "Shakespeare", year: 1611});
=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},
{title: "The Tempest", author: "Shakespeare", year: 1611}]
_.reject(list, predicate, [context])
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]
_.every(list, [predicate], [context])
Alias : all_.every([2, 4, 5], function(num) { return num % 2 == 0; });
=> false
_.some(list, [predicate], [context])
Alias : any_.some([null, 0, 'yes', false]);
=> true
_.contains(list, value, [fromIndex])
Aliases : include, includes_.contains([1, 2, 3], 3);
=> true
_.invoke(list, methodName, *arguments)
_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
=> [[1, 5, 7], [1, 2, 3]]
_.pluck(list, propertyName)
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]
_.max(list, [iteratee], [context])
< (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(list, [iteratee], [context])
< (note)
.var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
=> 2
_.sortBy(list, iteratee, [context])
< (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(list, iteratee, [context])
_.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(list, iteratee, [context])
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(list, iteratee, [context])
_.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
=> {odd: 3, even: 2}
_.shuffle(list)
_.shuffle([1, 2, 3, 4, 5, 6]);
=> [4, 1, 6, 3, 5, 2]
_.sample(list, [n])
_.sample([1, 2, 3, 4, 5, 6]);
=> 4
_.sample([1, 2, 3, 4, 5, 6], 3);
=> [1, 6, 2]
_.toArray(list)
(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
=> [2, 3, 4]
_.size(list)
_.size([1, 2, 3, 4, 5]);
=> 5
_.size({one: 1, two: 2, three: 3});
=> 3
_.partition(list, predicate)
_.partition([0, 1, 2, 3, 4, 5], isOdd);
=> [[1, 3, 5], [0, 2, 4]]
_.compact(list)
_.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]
_.first(array, [n])
Aliases : head, take_.first([5, 4, 3, 2, 1]);
=> 5
_.initial(array, [n])
_.initial([5, 4, 3, 2, 1]);
=> [5, 4, 3, 2]
_.last(array, [n])
_.last([5, 4, 3, 2, 1]);
=> 1
_.rest(array, [index])
Aliases : tail, drop_.rest([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]
_.indexOf(array, value, [isSorted])
< (note)
._.indexOf([1, 2, 3], 2);
=> 1
_.lastIndexOf(array, value, [fromIndex])
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
=> 4
_.sortedIndex(array, value, [iteratee], [context])
< (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(array, predicate, [context])
_.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(array, predicate, [context])
_.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
_.flatten(array, [depth])
_.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(array, *values)
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
_.union(*arrays)
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
_.intersection(*arrays)
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
_.difference(array, *others)
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
_.uniq(array, [isSorted], [iteratee])
Alias : unique===
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(*arrays)
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
_.unzip(array)
Alias: transpose_.unzip([["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]);
=> [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]]
_.object(list, [values])
_.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(array, length)
var partners = _.chunk(_.shuffle(kindergarten), 2);
=> [["Tyrone", "Elie"], ["Aidan", "Sam"], ["Katrina", "Billie"], ["Little Timmy"]]
_.range([start], stop, [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);
=> []
_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });
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 ... }
_.chain(obj)
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"
_.chain(obj).value()
_.chain([1, 2, 3]).reverse().value();
=> [3, 2, 1]
_.bind(function, object, *arguments)
var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name: 'moe'}, 'hi');
func();
=> 'hi: moe'
_.bindAll(object, *methodNames)
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(function, *arguments)
_.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(function, [hashFunction])
var fibonacci = _.memoize(function(n) {
return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});
_.delay(function, wait, *arguments)
var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
=> 'logged later' // Appears after one second.
_.once(function)
var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.
_.after(count, function)
var renderNotes = _.after(notes.length, render);
_.each(notes, function(note) {
note.asyncSave({success: renderNotes});
});
// renderNotes is run once, after all notes have saved.
_.before(count, function)
var monthlyMeeting = _.before(3, askForRaise);
monthlyMeeting();
monthlyMeeting();
monthlyMeeting();
// the result of any subsequent calls is the same as the second call
_.wrap(function, wrapper)
var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func) {
return "before, " + func("moe") + ", after";
});
hello();
=> 'before, hello: moe, after'
_.negate(predicate)
var isFalsy = _.negate(Boolean);
_.find([-2, -1, 0, 1, 2], isFalsy);
=> 0
_.compose(*functions)
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(function, [startIndex])​
var raceResults = _.restArguments(function(gold, silver, bronze, everyoneElse) {
_.each(everyoneElse, sendConsolations);
});
raceResults("Dopey", "Grumpy", "Happy", "Sneezy", "Bashful", "Sleepy", "Doc");
_.keys(object)
_.keys({one: 1, two: 2, three: 3});
=> ["one", "two", "three"]
_.allKeys(object)
function Stooge(name) {
this.name = name;
}
Stooge.prototype.silly = true;
_.allKeys(new Stooge("Moe"));
=> ["name", "silly"]
_.values(object)
_.values({one: 1, two: 2, three: 3});
=> [1, 2, 3]
_.mapObject(object, iteratee, [context])
_.mapObject({start: 5, end: 12}, function(val, key) {
return val + 5;
});
=> {start: 10, end: 17}
_.pairs(object)
_.pairs({one: 1, two: 2, three: 3});
=> [["one", 1], ["two", 2], ["three", 3]]
_.invert(object)
_.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"});
=> {Moses: "Moe", Louis: "Larry", Jerome: "Curly"};
_.create(prototype, props)
var moe = _.create(Stooge.prototype, {name: "Moe"});
_.functions(object)
Alias : methods_.functions(_);
=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
_.findKey(object, predicate, [context])
_.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(destination, *sources)
_.extend({name: 'moe'}, {age: 50});
=> {name: 'moe', age: 50}
_.extendOwn(destination, *sources)
Alias : assign_.pick(object, *keys)
_.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(object, *keys)
_.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(object, *defaults)
var iceCream = {flavor: "chocolate"};
_.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});
=> {flavor: "chocolate", sprinkles: "lots"}
_.clone(object)
_.clone({name: 'moe'});
=> {name: 'moe'};
_.tap(object, interceptor)
_.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(path)
_.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(object, path, [default])
_.get({a: 10}, 'a');
=> 10
_.get({a: [{b: 2}]}, ['a', 0, 'b']);
=> 2
_.get({a: 10}, 'b', 100);
=> 100
_.has(object, key)
_.has({a: 1, b: 2, c: 3}, "b");
=> true
_.property(path)
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(object)
_.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(attrs)
Alias: matchesvar ready = _.matcher({selected: true, visible: true});
var readyToGoList = _.filter(list, ready);
_.isEqual(object, other)
var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone = {name: 'moe', luckyNumbers: [13, 27, 34]};
stooge == clone;
=> false
_.isEqual(stooge, clone);
=> true
_.isMatch(object, properties)
var stooge = {name: 'moe', age: 32};
_.isMatch(stooge, {age: 32});
=> true
_.isEmpty(collection)
_.isEmpty([1, 2, 3]);
=> false
_.isEmpty({});
=> true
_.isElement(object)
_.isElement(jQuery('body')[0]);
=> true
​
_.isArray(object)
(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
_.isObject(value)
_.isObject({});
=> true
_.isObject(1);
=> false
_.isArguments(object)
(function(){ return _.isArguments(arguments); })(1, 2, 3);
=> true
_.isArguments([1,2,3]);
=> false
_.isFunction(object)
_.isFunction(alert);
=> true
_.isString(object)
_.isString("moe");
=> true
_.isNumber(object)
_.isNumber(8.4 * 5);
=> true
_.isFinite(object)
_.isFinite(-101);
=> true
_.isFinite(-Infinity);
=> false
_.isBoolean(object)
_.isBoolean(null);
=> false
_.isDate(object)
_.isDate(new Date());
=> true
_.isRegExp(object)
_.isRegExp(/moe/);
=> true
_.isError(object)
try {
throw new TypeError("Example");
} catch (o_O) {
_.isError(o_O);
}
=> true
_.isSymbol(object)
_.isSymbol(Symbol());
=> true
_.isMap(object)
_.isMap(new Map());
=> true
_.isWeakMap(object)
_.isWeakMap(new WeakMap());
=> true
_.isSet(object)
_.isSet(new Set());
=> true
_.isWeakSet(object)
_.isWeakSet(WeakSet());
=> true
_.isArrayBuffer(object)
_.isArrayBuffer(new ArrayBuffer(8));
=> true
_.isDataView(object)
_.isDataView(new DataView(new ArrayBuffer(8)));
=> true
_.isTypedArray(object)
_.isTypedArray(new Int8Array(8));
=> true
_.isNaN(object)
_.isNaN(NaN);
=> true
isNaN(undefined);
=> true
_.isNaN(undefined);
=> false
_.isNull(object)
_.isNull(null);
=> true
_.isNull(undefined);
=> false
_.isUndefined(value)
_.isUndefined(window.missingVariable);
=> true
_.noConflict()
_ variable
back to its previous owner. Returns a reference to the Underscore object.var underscore = _.noConflict();
_.noConflict
function is not present if you use the EcmaScript 6, AMD or CommonJS module system to import Underscore._.identity(value)
math: f(x) = x
var stooge = {name: 'moe'};
stooge === _.identity(stooge);
=> true
_.constant(value)
_.constant
.var stooge = {name: 'moe'};
stooge === _.constant(stooge)();
=> true
_.noop()
obj.initialize = _.noop;​
_.times(n, iteratee, [context])
_.times(3, function(n){ genie.grantWishNumber(n); });​
_.random(min, max)
_.random(0, 100);
=> 42
_.mixin(object)
_.mixin({
capitalize: function(string) {
return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
}
});
_("fabio").capitalize();
=> "Fabio"
_.uniqueId([prefix])
_.uniqueId('contact_');
=> 'contact_104'
_.escape(string)
&, <, >, ", `, and '
characters._.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
_.unescape(string)
_.unescape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
_.result(object, property, [defaultValue])
var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
_.result(object, 'meat', 'ham');
=> "ham"
_.now()
_.now();
=> 1392066795351
_.template(templateString, [settings])
<%= … %>
, 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><script></b>"
<%= ... %>
.var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge"
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var template = _.template("Hello {{ name }}!");
template({name: "Mustache"});
=> "Hello Mustache!"
_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
=> "Using 'with': no"
<script>
JST.project = <%= _.template(jstText).source %>;
</script>