Lo-Dash v0.9.2

Arrays

Chaining

Collections

Functions

Objects

Utilities

Properties

“Arrays” Methods

_.compact(array)

#

Creates an array with all falsey values of array removed. The values false, null, 0, "", undefined and NaN are all falsey.

Arguments

  1. array (Array): The array to compact.

Returns

(Array): Returns a new filtered array.

Example

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

_.difference(array [, array1, array2, ...])

#

Creates an array of array elements not present in the other arrays using strict equality for comparisons, i.e. ===.

Arguments

  1. array (Array): The array to process.
  2. [array1, array2, ...] (Array): Arrays to check.

Returns

(Array): Returns a new array of array elements not present in the other arrays.

Example

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

_.first(array [, n])

#

Gets the first element of the array. Pass n to return the first n elements of the array.

Aliases

head, take

Arguments

  1. array (Array): The array to query.
  2. [n] (Number): The number of elements to return.

Returns

(Mixed): Returns the first element or an array of the first n elements of array.

Example

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

_.flatten(array, shallow)

#

Flattens a nested array (the nesting can be to any depth). If shallow is truthy, array will only be flattened a single level.

Arguments

  1. array (Array): The array to compact.
  2. shallow (Boolean): A flag to indicate only flattening a single level.

Returns

(Array): Returns a new flattened array.

Example

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

_.indexOf(array, value [, fromIndex=0])

#

Gets the index at which the first occurrence of value is found using strict equality for comparisons, i.e. ===. If the array is already sorted, passing true for fromIndex will run a faster binary search.

Arguments

  1. array (Array): The array to search.
  2. value (Mixed): The value to search for.
  3. [fromIndex=0] (Boolean|Number): The index to search from or true to perform a binary search on a sorted array.

Returns

(Number): Returns the index of the matched value or -1.

Example

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

_.initial(array [, n=1])

#

Gets all but the last element of array. Pass n to exclude the last n elements from the result.

Arguments

  1. array (Array): The array to query.
  2. [n=1] (Number): The number of elements to exclude.

Returns

(Array): Returns all but the last element or n elements of array.

Example

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

_.intersection([array1, array2, ...])

#

Computes the intersection of all the passed-in arrays using strict equality for comparisons, i.e. ===.

Arguments

  1. [array1, array2, ...] (Array): Arrays to process.

Returns

(Array): Returns a new array of unique elements, in order, that are present in all of the arrays.

Example

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

_.last(array [, n])

#

Gets the last element of the array. Pass n to return the last n elements of the array.

Arguments

  1. array (Array): The array to query.
  2. [n] (Number): The number of elements to return.

Returns

(Mixed): Returns the last element or an array of the last n elements of array.

Example

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

_.lastIndexOf(array, value [, fromIndex=array.length-1])

#

Gets the index at which the last occurrence of value is found using strict equality for comparisons, i.e. ===. If fromIndex is negative, it is used as the offset from the end of the collection.

Arguments

  1. array (Array): The array to search.
  2. value (Mixed): The value to search for.
  3. [fromIndex=array.length-1] (Number): The index to search from.

Returns

(Number): Returns the index of the matched value or -1.

Example

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

_.object(keys [, values=[]])

#

Creates an object composed from arrays of keys and values. Pass either a single two dimensional array, i.e. [[key1, value1], [key2, value2]], or two arrays, one of keys and one of corresponding values.

Arguments

  1. keys (Array): The array of keys.
  2. [values=[]] (Array): The array of values.

Returns

(Object): Returns an object composed of the given keys and corresponding values.

Example

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

_.range([start=0], end [, step=1])

#

Creates an array of numbers (positive and/or negative) progressing from start up to but not including stop. This method is a port of Python’s range() function. See http://docs.python.org/library/functions.html#range.

Arguments

  1. [start=0] (Number): The start of the range.
  2. end (Number): The end of the range.
  3. [step=1] (Number): The value to increment or descrement by.

Returns

(Array): Returns a new range array.

Example

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

_.rest(array [, n=1])

#

The opposite of _.initial, this method gets all but the first value of array. Pass n to exclude the first n values from the result.

Aliases

drop, tail

Arguments

  1. array (Array): The array to query.
  2. [n=1] (Number): The number of elements to exclude.

Returns

(Array): Returns all but the first value or n values of array.

Example

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

_.sortedIndex(array, value [, callback=identity|property, thisArg])

#

Uses a binary search to determine the smallest index at which the value should be inserted into array in order to maintain the sort order of the sorted array. If callback is passed, it will be executed for value and each element in array to compute their sort ranking. The callback is bound to thisArg and invoked with one argument; (value). The callback argument may also be the name of a property to order by.

Arguments

  1. array (Array): The array to iterate over.
  2. value (Mixed): The value to evaluate.
  3. [callback=identity|property] (Function|String): The function called per iteration or property name to order by.
  4. [thisArg] (Mixed): The this binding of callback.

Returns

(Number): Returns the index at which the value should be inserted into array.

Example

  1. _.sortedIndex([20, 30, 50], 40);
  2. // => 2
  3. _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
  4. // => 2
  5. var dict = {
  6. 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
  7. };
  8. _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  9. return dict.wordToNumber[word];
  10. });
  11. // => 2
  12. _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
  13. return this.wordToNumber[word];
  14. }, dict);
  15. // => 2

_.union([array1, array2, ...])

#

Computes the union of the passed-in arrays using strict equality for comparisons, i.e. ===.

Arguments

  1. [array1, array2, ...] (Array): Arrays to process.

Returns

(Array): Returns a new array of unique values, in order, that are present in one or more of the arrays.

Example

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

_.uniq(array [, isSorted=false, callback=identity, thisArg])

#

Creates a duplicate-value-free version of the array using strict equality for comparisons, i.e. ===. If the array is already sorted, passing true for isSorted will run a faster algorithm. If callback is passed, each element of array is passed through a callbackbefore uniqueness is computed. Thecallbackis bound tothisArg` and invoked with three arguments; (value, index, array).

Aliases

unique

Arguments

  1. array (Array): The array to process.
  2. [isSorted=false] (Boolean): A flag to indicate that the array is already sorted.
  3. [callback=identity] (Function): The function called per iteration.
  4. [thisArg] (Mixed): The this binding of callback.

Returns

(Array): Returns a duplicate-value-free array.

Example

  1. _.uniq([1, 2, 1, 3, 1]);
  2. // => [1, 2, 3]
  3. _.uniq([1, 1, 2, 2, 3], true);
  4. // => [1, 2, 3]
  5. _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); });
  6. // => [1, 2, 3]
  7. _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math);
  8. // => [1, 2, 3]

_.without(array [, value1, value2, ...])

#

Creates an array with all occurrences of the passed values removed using strict equality for comparisons, i.e. ===.

Arguments

  1. array (Array): The array to filter.
  2. [value1, value2, ...] (Mixed): Values to remove.

Returns

(Array): Returns a new filtered array.

Example

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

_.zip([array1, array2, ...])

#

Groups the elements of each array at their corresponding indexes. Useful for separate data sources that are coordinated through matching array indexes. For a matrix of nested arrays, _.zip.apply(...) can transpose the matrix in a similar fashion.

Arguments

  1. [array1, array2, ...] (Array): Arrays to process.

Returns

(Array): Returns a new array of grouped elements.

Example

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

“Chaining” Methods

_(value)

#

The lodash function.

Arguments

  1. value (Mixed): The value to wrap in a lodash instance.

Returns

(Object): Returns a lodash instance.


_.chain(value)

#

Wraps the value in a lodash wrapper object.

Arguments

  1. value (Mixed): The value to wrap.

Returns

(Object): Returns the wrapper object.

Example

  1. var stooges = [
  2. { 'name': 'moe', 'age': 40 },
  3. { 'name': 'larry', 'age': 50 },
  4. { 'name': 'curly', 'age': 60 }
  5. ];
  6. var youngest = _.chain(stooges)
  7. .sortBy(function(stooge) { return stooge.age; })
  8. .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
  9. .first()
  10. .value();
  11. // => 'moe is 40'

_.tap(value, interceptor)

#

Invokes interceptor with the value as the first argument, and then returns value. The purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

Arguments

  1. value (Mixed): The value to pass to interceptor.
  2. interceptor (Function): The function to invoke.

Returns

(Mixed): Returns value.

Example

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

_.prototype.chain()

#

Enables method chaining on the wrapper object.

Returns

(Mixed): Returns the wrapper object.

Example

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

_.prototype.value()

#

Extracts the wrapped value.

Returns

(Mixed): Returns the wrapped value.

Example

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

“Collections” Methods

_.contains(collection, target [, fromIndex=0])

#

Checks if a given target element is present in a collection using strict equality for comparisons, i.e. ===. If fromIndex is negative, it is used as the offset from the end of the collection.

Aliases

include

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. target (Mixed): The value to check for.
  3. [fromIndex=0] (Number): The index to search from.

Returns

(Boolean): Returns true if the target element is found, else false.

Example

  1. _.contains([1, 2, 3], 1);
  2. // => true
  3. _.contains([1, 2, 3], 1, 2);
  4. // => false
  5. _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
  6. // => true
  7. _.contains('curly', 'ur');
  8. // => true

_.countBy(collection, callback|property [, thisArg])

#

Creates an object composed of keys returned from running each element of collection through a callback. The corresponding value of each key is the number of times the key was returned by callback. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection). The callback argument may also be the name of a property to count by (e.g. ‘length’).

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. callback|property (Function|String): The function called per iteration or property name to count by.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Object): Returns the composed aggregate object.

Example

  1. _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
  2. // => { '4': 1, '6': 2 }
  3. _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  4. // => { '4': 1, '6': 2 }
  5. _.countBy(['one', 'two', 'three'], 'length');
  6. // => { '3': 2, '5': 1 }

_.every(collection [, callback=identity, thisArg])

#

Checks if the callback returns a truthy value for all elements of a collection. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection).

Aliases

all

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. [callback=identity] (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Boolean): Returns true if all elements pass the callback check, else false.

Example

  1. _.every([true, 1, null, 'yes'], Boolean);
  2. // => false

_.filter(collection [, callback=identity, thisArg])

#

Examines each element in a collection, returning an array of all elements the callback returns truthy for. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection).

Aliases

select

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. [callback=identity] (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Array): Returns a new array of elements that passed the callback check.

Example

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

_.find(collection, callback [, thisArg])

#

Examines each element in a collection, returning the first one the callback returns truthy for. The function returns as soon as it finds an acceptable element, and does not iterate over the entire collection. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection).

Aliases

detect

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. callback (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Mixed): Returns the element that passed the callback check, else undefined.

Example

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

_.forEach(collection, callback [, thisArg])

#

Iterates over a collection, executing the callback for each element in the collection. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection). Callbacks may exit iteration early by explicitly returning false.

Aliases

each

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. callback (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Array, Object, String): Returns collection.

Example

  1. _([1, 2, 3]).forEach(alert).join(',');
  2. // => alerts each number and returns '1,2,3'
  3. _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
  4. // => alerts each number (order is not guaranteed)

_.groupBy(collection, callback|property [, thisArg])

#

Creates an object composed of keys returned from running each element of collection through a callback. The corresponding value of each key is an array of elements passed to callback that returned the key. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection). The callback argument may also be the name of a property to group by (e.g. ‘length’).

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. callback|property (Function|String): The function called per iteration or property name to group by.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Object): Returns the composed aggregate object.

Example

  1. _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
  2. // => { '4': [4.2], '6': [6.1, 6.4] }
  3. _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
  4. // => { '4': [4.2], '6': [6.1, 6.4] }
  5. _.groupBy(['one', 'two', 'three'], 'length');
  6. // => { '3': ['one', 'two'], '5': ['three'] }

_.invoke(collection, methodName [, arg1, arg2, ...])

#

Invokes the method named by methodName on each element in the collection, returning an array of the results of each invoked method. Additional arguments will be passed to each invoked method. If methodName is a function it will be invoked for, and this bound to, each element in the collection.

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. methodName (Function|String): The name of the method to invoke or the function invoked per iteration.
  3. [arg1, arg2, ...] (Mixed): Arguments to invoke the method with.

Returns

(Array): Returns a new array of the results of each invoked method.

Example

  1. _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  2. // => [[1, 5, 7], [1, 2, 3]]
  3. _.invoke([123, 456], String.prototype.split, '');
  4. // => [['1', '2', '3'], ['4', '5', '6']]

_.map(collection [, callback=identity, thisArg])

#

Creates an array of values by running each element in the collection through a callback. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection).

Aliases

collect

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. [callback=identity] (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Array): Returns a new array of the results of each callback execution.

Example

  1. _.map([1, 2, 3], function(num) { return num * 3; });
  2. // => [3, 6, 9]
  3. _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
  4. // => [3, 6, 9] (order is not guaranteed)

_.max(collection [, callback, thisArg])

#

Retrieves the maximum value of an array. If callback is passed, it will be executed for each value in the array to generate the criterion by which the value is ranked. The callback is bound to thisArg and invoked with three arguments; (value, index, collection).

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. [callback] (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Mixed): Returns the maximum value.

Example

  1. var stooges = [
  2. { 'name': 'moe', 'age': 40 },
  3. { 'name': 'larry', 'age': 50 },
  4. { 'name': 'curly', 'age': 60 }
  5. ];
  6. _.max(stooges, function(stooge) { return stooge.age; });
  7. // => { 'name': 'curly', 'age': 60 };

_.min(collection [, callback, thisArg])

#

Retrieves the minimum value of an array. If callback is passed, it will be executed for each value in the array to generate the criterion by which the value is ranked. The callback is bound to thisArg and invoked with three arguments; (value, index, collection).

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. [callback] (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Mixed): Returns the minimum value.

Example

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

_.pluck(collection, property)

#

Retrieves the value of a specified property from all elements in the collection.

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. property (String): The property to pluck.

Returns

(Array): Returns a new array of property values.

Example

  1. var stooges = [
  2. { 'name': 'moe', 'age': 40 },
  3. { 'name': 'larry', 'age': 50 },
  4. { 'name': 'curly', 'age': 60 }
  5. ];
  6. _.pluck(stooges, 'name');
  7. // => ['moe', 'larry', 'curly']

_.reduce(collection, callback [, accumulator, thisArg])

#

Boils down a collection to a single value. The initial state of the reduction is accumulator and each successive step of it should be returned by the callback. The callback is bound to thisArg and invoked with 4 arguments; for arrays they are (accumulator, value, index|key, collection).

Aliases

foldl, inject

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. callback (Function): The function called per iteration.
  3. [accumulator] (Mixed): Initial value of the accumulator.
  4. [thisArg] (Mixed): The this binding of callback.

Returns

(Mixed): Returns the accumulated value.

Example

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

_.reduceRight(collection, callback [, accumulator, thisArg])

#

The right-associative version of _.reduce.

Aliases

foldr

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. callback (Function): The function called per iteration.
  3. [accumulator] (Mixed): Initial value of the accumulator.
  4. [thisArg] (Mixed): The this binding of callback.

Returns

(Mixed): Returns the accumulated value.

Example

  1. var list = [[0, 1], [2, 3], [4, 5]];
  2. var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  3. // => [4, 5, 2, 3, 0, 1]

_.reject(collection [, callback=identity, thisArg])

#

The opposite of _.filter, this method returns the values of a collection that callback does not return truthy for.

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. [callback=identity] (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Array): Returns a new array of elements that did not pass the callback check.

Example

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

_.shuffle(collection)

#

Creates an array of shuffled array values, using a version of the Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.

Arguments

  1. collection (Array|Object|String): The collection to shuffle.

Returns

(Array): Returns a new shuffled collection.

Example

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

_.size(collection)

#

Gets the size of the collection by returning collection.length for arrays and array-like objects or the number of own enumerable properties for objects.

Arguments

  1. collection (Array|Object|String): The collection to inspect.

Returns

(Number): Returns collection.length or number of own enumerable properties.

Example

  1. _.size([1, 2]);
  2. // => 2
  3. _.size({ 'one': 1, 'two': 2, 'three': 3 });
  4. // => 3
  5. _.size('curly');
  6. // => 5

_.some(collection [, callback=identity, thisArg])

#

Checks if the callback returns a truthy value for any element of a collection. The function returns as soon as it finds passing value, and does not iterate over the entire collection. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection).

Aliases

any

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. [callback=identity] (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Boolean): Returns true if any element passes the callback check, else false.

Example

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

_.sortBy(collection, callback|property [, thisArg])

#

Creates an array, stable sorted in ascending order by the results of running each element of collection through a callback. The callback is bound to thisArg and invoked with three arguments; (value, index|key, collection). The callback argument may also be the name of a property to sort by (e.g. ‘length’).

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. callback|property (Function|String): The function called per iteration or property name to sort by.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Array): Returns a new array of sorted elements.

Example

  1. _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
  2. // => [3, 1, 2]
  3. _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
  4. // => [3, 1, 2]
  5. _.sortBy(['larry', 'brendan', 'moe'], 'length');
  6. // => ['moe', 'larry', 'brendan']

_.toArray(collection)

#

Converts the collection, to an array.

Arguments

  1. collection (Array|Object|String): The collection to convert.

Returns

(Array): Returns the new converted array.

Example

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

_.where(collection, properties)

#

Examines each element in a collection, returning an array of all elements that contain the given properties.

Arguments

  1. collection (Array|Object|String): The collection to iterate over.
  2. properties (Object): The object of property values to filter by.

Returns

(Array): Returns a new array of elements that contain the given properties.

Example

  1. var stooges = [
  2. { 'name': 'moe', 'age': 40 },
  3. { 'name': 'larry', 'age': 50 },
  4. { 'name': 'curly', 'age': 60 }
  5. ];
  6. _.where(stooges, { 'age': 40 });
  7. // => [{ 'name': 'moe', 'age': 40 }]

“Functions” Methods

_.after(n, func)

#

Creates a function that is restricted to executing func only after it is called n times. The func is executed with the this binding of the created function.

Arguments

  1. n (Number): The number of times the function must be called before it is executed.
  2. func (Function): The function to restrict.

Returns

(Function): Returns the new restricted function.

Example

  1. var renderNotes = _.after(notes.length, render);
  2. _.forEach(notes, function(note) {
  3. note.asyncSave({ 'success': renderNotes });
  4. });
  5. // `renderNotes` is run once, after all notes have saved

_.bind(func [, thisArg, arg1, arg2, ...])

#

Creates a function that, when called, invokes func with the this binding of thisArg and prepends any additional bind arguments to those passed to the bound function.

Arguments

  1. func (Function): The function to bind.
  2. [thisArg] (Mixed): The this binding of func.
  3. [arg1, arg2, ...] (Mixed): Arguments to be partially applied.

Returns

(Function): Returns the new bound function.

Example

  1. var func = function(greeting) {
  2. return greeting + ' ' + this.name;
  3. };
  4. func = _.bind(func, { 'name': 'moe' }, 'hi');
  5. func();
  6. // => 'hi moe'

_.bindAll(object [, methodName1, methodName2, ...])

#

Binds methods on object to object, overwriting the existing method. If no method names are provided, all the function properties of object will be bound.

Arguments

  1. object (Object): The object to bind and assign the bound methods to.
  2. [methodName1, methodName2, ...] (String): Method names on the object to bind.

Returns

(Object): Returns object.

Example

  1. var buttonView = {
  2. 'label': 'lodash',
  3. 'onClick': function() { alert('clicked: ' + this.label); }
  4. };
  5. _.bindAll(buttonView);
  6. jQuery('#lodash_button').on('click', buttonView.onClick);
  7. // => When the button is clicked, `this.label` will have the correct value

_.compose([func1, func2, ...])

#

Creates a function that is the composition of the passed 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())). Each function is executed with the this binding of the composed function.

Arguments

  1. [func1, func2, ...] (Function): Functions to compose.

Returns

(Function): Returns the new composed function.

Example

  1. var greet = function(name) { return 'hi: ' + name; };
  2. var exclaim = function(statement) { return statement + '!'; };
  3. var welcome = _.compose(exclaim, greet);
  4. welcome('moe');
  5. // => 'hi: moe!'

_.debounce(func, wait, immediate)

#

Creates a function that will delay the execution of func until after wait milliseconds have elapsed since the last time it was invoked. Pass true for immediate to cause debounce to invoke func on the leading, instead of the trailing, edge of the wait timeout. Subsequent calls to the debounced function will return the result of the last func call.

Arguments

  1. func (Function): The function to debounce.
  2. wait (Number): The number of milliseconds to delay.
  3. immediate (Boolean): A flag to indicate execution is on the leading edge of the timeout.

Returns

(Function): Returns the new debounced function.

Example

  1. var lazyLayout = _.debounce(calculateLayout, 300);
  2. jQuery(window).on('resize', lazyLayout);

_.defer(func [, arg1, arg2, ...])

#

Defers executing the func function until the current call stack has cleared. Additional arguments will be passed to func when it is invoked.

Arguments

  1. func (Function): The function to defer.
  2. [arg1, arg2, ...] (Mixed): Arguments to invoke the function with.

Returns

(Number): Returns the setTimeout timeout id.

Example

  1. _.defer(function() { alert('deferred'); });
  2. // returns from the function before `alert` is called

_.delay(func, wait [, arg1, arg2, ...])

#

Executes the func function after wait milliseconds. Additional arguments will be passed to func when it is invoked.

Arguments

  1. func (Function): The function to delay.
  2. wait (Number): The number of milliseconds to delay execution.
  3. [arg1, arg2, ...] (Mixed): Arguments to invoke the function with.

Returns

(Number): Returns the setTimeout timeout id.

Example

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

_.lateBind(object, methodName [, arg1, arg2, ...])

#

Creates a function that, when called, invokes object[methodName] and prepends any additional lateBind arguments to those passed to the bound function. This method differs from _.bind by allowing bound functions to reference methods that will be redefined or don’t yet exist.

Arguments

  1. object (Object): The object the method belongs to.
  2. methodName (String): The method name.
  3. [arg1, arg2, ...] (Mixed): Arguments to be partially applied.

Returns

(Function): Returns the new bound function.

Example

  1. var object = {
  2. 'name': 'moe',
  3. 'greet': function(greeting) {
  4. return greeting + ' ' + this.name;
  5. }
  6. };
  7. var func = _.lateBind(object, 'greet', 'hi');
  8. func();
  9. // => 'hi moe'
  10. object.greet = function(greeting) {
  11. return greeting + ', ' + this.name + '!';
  12. };
  13. func();
  14. // => 'hi, moe!'

_.memoize(func [, resolver])

#

Creates a function that memoizes the result of func. If resolver is passed, it will be used to determine the cache key for storing the result based on the arguments passed to the memoized function. By default, the first argument passed to the memoized function is used as the cache key. The func is executed with the this binding of the memoized function.

Arguments

  1. func (Function): The function to have its output memoized.
  2. [resolver] (Function): A function used to resolve the cache key.

Returns

(Function): Returns the new memoizing function.

Example

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

_.once(func)

#

Creates a function that is restricted to execute func once. Repeat calls to the function will return the value of the first call. The func is executed with the this binding of the created function.

Arguments

  1. func (Function): The function to restrict.

Returns

(Function): Returns the new restricted function.

Example

  1. var initialize = _.once(createApplication);
  2. initialize();
  3. initialize();
  4. // Application is only created once.

_.partial(func [, arg1, arg2, ...])

#

Creates a function that, when called, invokes func with any additional partial arguments prepended to those passed to the new function. This method is similar to bind, except it does not alter the this binding.

Arguments

  1. func (Function): The function to partially apply arguments to.
  2. [arg1, arg2, ...] (Mixed): Arguments to be partially applied.

Returns

(Function): Returns the new partially applied function.

Example

  1. var greet = function(greeting, name) { return greeting + ': ' + name; };
  2. var hi = _.partial(greet, 'hi');
  3. hi('moe');
  4. // => 'hi: moe'

_.throttle(func, wait)

#

Creates a function that, when executed, will only call the func function at most once per every wait milliseconds. If the throttled function is invoked more than once during the wait timeout, func will also be called on the trailing edge of the timeout. Subsequent calls to the throttled function will return the result of the last func call.

Arguments

  1. func (Function): The function to throttle.
  2. wait (Number): The number of milliseconds to throttle executions to.

Returns

(Function): Returns the new throttled function.

Example

  1. var throttled = _.throttle(updatePosition, 100);
  2. jQuery(window).on('scroll', throttled);

_.wrap(value, wrapper)

#

Creates a function that passes value to the wrapper function as its first argument. Additional arguments passed to the function are appended to those passed to the wrapper function. The wrapper is executed with the this binding of the created function.

Arguments

  1. value (Mixed): The value to wrap.
  2. wrapper (Function): The wrapper function.

Returns

(Function): Returns the new function.

Example

  1. var hello = function(name) { return 'hello ' + name; };
  2. hello = _.wrap(hello, function(func) {
  3. return 'before, ' + func('moe') + ', after';
  4. });
  5. hello();
  6. // => 'before, hello moe, after'

“Objects” Methods

_.clone(value, deep)

#

Creates a clone of value. If deep is true, all nested objects will also be cloned otherwise they will be assigned by reference. Functions, DOM nodes, arguments objects, and objects created by constructors other than Object are not cloned.

Arguments

  1. value (Mixed): The value to clone.
  2. deep (Boolean): A flag to indicate a deep clone.

Returns

(Mixed): Returns the cloned value.

Example

  1. var stooges = [
  2. { 'name': 'moe', 'age': 40 },
  3. { 'name': 'larry', 'age': 50 },
  4. { 'name': 'curly', 'age': 60 }
  5. ];
  6. _.clone({ 'name': 'moe' });
  7. // => { 'name': 'moe' }
  8. var shallow = _.clone(stooges);
  9. shallow[0] === stooges[0];
  10. // => true
  11. var deep = _.clone(stooges, true);
  12. shallow[0] === stooges[0];
  13. // => false

_.defaults(object [, default1, default2, ...])

#

Assigns enumerable properties of the default object(s) to the destination object for all destination properties that resolve to null/undefined. Once a property is set, additional defaults of the same property will be ignored.

Arguments

  1. object (Object): The destination object.
  2. [default1, default2, ...] (Object): The default objects.

Returns

(Object): Returns the destination object.

Example

  1. var iceCream = { 'flavor': 'chocolate' };
  2. _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' });
  3. // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' }

_.extend(object [, source1, source2, ...])

#

Assigns enumerable properties of the source object(s) to the destination object. Subsequent sources will overwrite propery assignments of previous sources.

Arguments

  1. object (Object): The destination object.
  2. [source1, source2, ...] (Object): The source objects.

Returns

(Object): Returns the destination object.

Example

  1. _.extend({ 'name': 'moe' }, { 'age': 40 });
  2. // => { 'name': 'moe', 'age': 40 }

_.forIn(object, callback [, thisArg])

#

Iterates over object‘s own and inherited enumerable properties, executing the callback for each property. The callback is bound to thisArg and invoked with three arguments; (value, key, object). Callbacks may exit iteration early by explicitly returning false.

Arguments

  1. object (Object): The object to iterate over.
  2. callback (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Object): Returns object.

Example

  1. function Dog(name) {
  2. this.name = name;
  3. }
  4. Dog.prototype.bark = function() {
  5. alert('Woof, woof!');
  6. };
  7. _.forIn(new Dog('Dagny'), function(value, key) {
  8. alert(key);
  9. });
  10. // => alerts 'name' and 'bark' (order is not guaranteed)

_.forOwn(object, callback [, thisArg])

#

Iterates over object‘s own enumerable properties, executing the callback for each property. The callback is bound to thisArg and invoked with three arguments; (value, key, object). Callbacks may exit iteration early by explicitly returning false.

Arguments

  1. object (Object): The object to iterate over.
  2. callback (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Object): Returns object.

Example

  1. _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
  2. alert(key);
  3. });
  4. // => alerts '0', '1', and 'length' (order is not guaranteed)

_.functions(object)

#

Creates a sorted array of all enumerable properties, own and inherited, of object that have function values.

Aliases

methods

Arguments

  1. object (Object): The object to inspect.

Returns

(Array): Returns a new array of property names that have function values.

Example

  1. _.functions(_);
  2. // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]

_.has(object, property)

#

Checks if the specified object property exists and is a direct property, instead of an inherited property.

Arguments

  1. object (Object): The object to check.
  2. property (String): The property to check for.

Returns

(Boolean): Returns true if key is a direct property, else false.

Example

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

_.invert(object)

#

Creates an object composed of the inverted keys and values of the given object.

Arguments

  1. object (Object): The object to invert.

Returns

(Object): Returns the created inverted object.

Example

  1. _.invert({ 'first': 'Moe', 'second': 'Larry', 'third': 'Curly' });
  2. // => { 'Moe': 'first', 'Larry': 'second', 'Curly': 'third' } (order is not guaranteed)

_.isArguments(value)

#

Checks if value is an arguments object.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is an arguments object, else false.

Example

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

_.isArray(value)

#

Checks if value is an array.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is an array, else false.

Example

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

_.isBoolean(value)

#

Checks if value is a boolean (true or false) value.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a boolean value, else false.

Example

  1. _.isBoolean(null);
  2. // => false

_.isDate(value)

#

Checks if value is a date.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a date, else false.

Example

  1. _.isDate(new Date);
  2. // => true

_.isElement(value)

#

Checks if value is a DOM element.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a DOM element, else false.

Example

  1. _.isElement(document.body);
  2. // => true

_.isEmpty(value)

#

Checks if value is empty. Arrays, strings, or arguments objects with a length of 0 and objects with no own enumerable properties are considered “empty”.

Arguments

  1. value (Array|Object|String): The value to inspect.

Returns

(Boolean): Returns true if the value is empty, else false.

Example

  1. _.isEmpty([1, 2, 3]);
  2. // => false
  3. _.isEmpty({});
  4. // => true
  5. _.isEmpty('');
  6. // => true

_.isEqual(a, b)

#

Performs a deep comparison between two values to determine if they are equivalent to each other.

Arguments

  1. a (Mixed): The value to compare.
  2. b (Mixed): The other value to compare.

Returns

(Boolean): Returns true if the values are equvalent, else false.

Example

  1. var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  2. var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
  3. moe == clone;
  4. // => false
  5. _.isEqual(moe, clone);
  6. // => true

_.isFinite(value)

#

Checks if value is, or can be coerced to, a finite number. Note: This is not the same as native isFinite, which will return true for booleans and empty strings. See http://es5.github.com/#x15.1.2.5.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a finite number, else false.

Example

  1. _.isFinite(-101);
  2. // => true
  3. _.isFinite('10');
  4. // => true
  5. _.isFinite(true);
  6. // => false
  7. _.isFinite('');
  8. // => false
  9. _.isFinite(Infinity);
  10. // => false

_.isFunction(value)

#

Checks if value is a function.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a function, else false.

Example

  1. _.isFunction(_);
  2. // => true

_.isNaN(value)

#

Checks if value is NaN. Note: This is not the same as native isNaN, which will return true for undefined and other values. See http://es5.github.com/#x15.1.2.4.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is NaN, else false.

Example

  1. _.isNaN(NaN);
  2. // => true
  3. _.isNaN(new Number(NaN));
  4. // => true
  5. isNaN(undefined);
  6. // => true
  7. _.isNaN(undefined);
  8. // => false

_.isNull(value)

#

Checks if value is null.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is null, else false.

Example

  1. _.isNull(null);
  2. // => true
  3. _.isNull(undefined);
  4. // => false

_.isNumber(value)

#

Checks if value is a number.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a number, else false.

Example

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

_.isObject(value)

#

Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is an object, else false.

Example

  1. _.isObject({});
  2. // => true
  3. _.isObject([1, 2, 3]);
  4. // => true
  5. _.isObject(1);
  6. // => false

_.isPlainObject(value)

#

Checks if a given value is an object created by the Object constructor.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if value is a plain object, else false.

Example

  1. function Stooge(name, age) {
  2. this.name = name;
  3. this.age = age;
  4. }
  5. _.isPlainObject(new Stooge('moe', 40));
  6. // => false
  7. _.isPlainObject([1, 2, 3]);
  8. // => false
  9. _.isPlainObject({ 'name': 'moe', 'age': 40 });
  10. // => true

_.isRegExp(value)

#

Checks if value is a regular expression.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a regular expression, else false.

Example

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

_.isString(value)

#

Checks if value is a string.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is a string, else false.

Example

  1. _.isString('moe');
  2. // => true

_.isUndefined(value)

#

Checks if value is undefined.

Arguments

  1. value (Mixed): The value to check.

Returns

(Boolean): Returns true if the value is undefined, else false.

Example

  1. _.isUndefined(void 0);
  2. // => true

_.keys(object)

#

Creates an array composed of the own enumerable property names of object.

Arguments

  1. object (Object): The object to inspect.

Returns

(Array): Returns a new array of property names.

Example

  1. _.keys({ 'one': 1, 'two': 2, 'three': 3 });
  2. // => ['one', 'two', 'three'] (order is not guaranteed)

_.merge(object [, source1, source2, ...])

#

Merges enumerable properties of the source object(s) into the destination object. Subsequent sources will overwrite propery assignments of previous sources.

Arguments

  1. object (Object): The destination object.
  2. [source1, source2, ...] (Object): The source objects.

Returns

(Object): Returns the destination object.

Example

  1. var stooges = [
  2. { 'name': 'moe' },
  3. { 'name': 'larry' }
  4. ];
  5. var ages = [
  6. { 'age': 40 },
  7. { 'age': 50 }
  8. ];
  9. _.merge(stooges, ages);
  10. // => [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }]

_.omit(object, callback|[prop1, prop2, ..., thisArg])

#

Creates a shallow clone of object excluding the specified properties. Property names may be specified as individual arguments or as arrays of property names. If callback is passed, it will be executed for each property in the object, omitting the properties callback returns truthy for. The callback is bound to thisArg and invoked with three arguments; (value, key, object).

Arguments

  1. object (Object): The source object.
  2. callback|[prop1, prop2, ...] (Function|String): The properties to omit or the function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Object): Returns an object without the omitted properties.

Example

  1. _.omit({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid');
  2. // => { 'name': 'moe', 'age': 40 }
  3. _.omit({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
  4. return key.charAt(0) == '_';
  5. });
  6. // => { 'name': 'moe' }

_.pairs(object)

#

Creates a two dimensional array of the given object’s key-value pairs, i.e. [[key1, value1], [key2, value2]].

Arguments

  1. object (Object): The object to inspect.

Returns

(Array): Returns new array of key-value pairs.

Example

  1. _.pairs({ 'moe': 30, 'larry': 40, 'curly': 50 });
  2. // => [['moe', 30], ['larry', 40], ['curly', 50]] (order is not guaranteed)

_.pick(object, callback|[prop1, prop2, ..., thisArg])

#

Creates a shallow clone of object composed of the specified properties. Property names may be specified as individual arguments or as arrays of property names. If callback is passed, it will be executed for each property in the object, picking the properties callback returns truthy for. The callback is bound to thisArg and invoked with three arguments; (value, key, object).

Arguments

  1. object (Object): The source object.
  2. callback|[prop1, prop2, ...] (Function|String): The properties to pick or the function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Object): Returns an object composed of the picked properties.

Example

  1. _.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age');
  2. // => { 'name': 'moe', 'age': 40 }
  3. _.pick({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) {
  4. return key.charAt(0) != '_';
  5. });
  6. // => { 'name': 'moe' }

_.values(object)

#

Creates an array composed of the own enumerable property values of object.

Arguments

  1. object (Object): The object to inspect.

Returns

(Array): Returns a new array of property values.

Example

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

“Utilities” Methods

_.escape(string)

#

Converts the characters &, <, >, ", and ' in string to their corresponding HTML entities.

Arguments

  1. string (String): The string to escape.

Returns

(String): Returns the escaped string.

Example

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

_.identity(value)

#

This function returns the first argument passed to it. Note: It is used throughout Lo-Dash as a default callback.

Arguments

  1. value (Mixed): Any value.

Returns

(Mixed): Returns value.

Example

  1. var moe = { 'name': 'moe' };
  2. moe === _.identity(moe);
  3. // => true

_.mixin(object)

#

Adds functions properties of object to the lodash function and chainable wrapper.

Arguments

  1. object (Object): The object of function properties to add to lodash.

Example

  1. _.mixin({
  2. 'capitalize': function(string) {
  3. return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  4. }
  5. });
  6. _.capitalize('larry');
  7. // => 'Larry'
  8. _('curly').capitalize();
  9. // => 'Curly'

_.noConflict()

#

Reverts the ‘_’ variable to its previous value and returns a reference to the lodash function.

Returns

(Function): Returns the lodash function.

Example

  1. var lodash = _.noConflict();

_.random([min=0, max=1])

#

Produces a random number between min and max (inclusive). If only one argument is passed, a number between 0 and the given number will be returned.

Arguments

  1. [min=0] (Number): The minimum possible value.
  2. [max=1] (Number): The maximum possible value.

Returns

(Number): Returns a random number.

Example

  1. _.random(0, 5);
  2. // => a number between 1 and 5
  3. _.random(5);
  4. // => also a number between 1 and 5

_.result(object, property)

#

Resolves the value of property on object. If property is a function it will be invoked and its result returned, else the property value is returned. If object is falsey, then null is returned.

Arguments

  1. object (Object): The object to inspect.
  2. property (String): The property to get the value of.

Returns

(Mixed): Returns the resolved value.

Example

  1. var object = {
  2. 'cheese': 'crumpets',
  3. 'stuff': function() {
  4. return 'nonsense';
  5. }
  6. };
  7. _.result(object, 'cheese');
  8. // => 'crumpets'
  9. _.result(object, 'stuff');
  10. // => 'nonsense'

_.template(text, data, options)

#

A micro-templating method that handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. Note: In the development build _.template utilizes sourceURLs for easier debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl Note: Lo-Dash may be used in Chrome extensions by either creating a lodash csp build and avoiding _.template use, or loading Lo-Dash in a sandboxed page. See http://developer.chrome.com/trunk/extensions/sandboxingEval.html

Arguments

  1. text (String): The template text.
  2. data (Obect): The data object used to populate the text.
  3. options (Object): The options object. escape - The “escape” delimiter regexp. evaluate - The “evaluate” delimiter regexp. interpolate - The “interpolate” delimiter regexp. sourceURL - The sourceURL of the template’s compiled source. variable - The data object variable name.

Returns

(Function, String): Returns a compiled function when no data object is given, else it returns the interpolated text.

Example

  1. // using a compiled template
  2. var compiled = _.template('hello <%= name %>');
  3. compiled({ 'name': 'moe' });
  4. // => 'hello moe'
  5. var list = '<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>';
  6. _.template(list, { 'people': ['moe', 'larry', 'curly'] });
  7. // => '<li>moe</li><li>larry</li><li>curly</li>'
  8. // using the "escape" delimiter to escape HTML in data property values
  9. _.template('<b><%- value %></b>', { 'value': '<script>' });
  10. // => '<b>&lt;script&gt;</b>'
  11. // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
  12. _.template('hello ${ name }', { 'name': 'curly' });
  13. // => 'hello curly'
  14. // using the internal `print` function in "evaluate" delimiters
  15. _.template('<% print("hello " + epithet); %>!', { 'epithet': 'stooge' });
  16. // => 'hello stooge!'
  17. // using custom template delimiters
  18. _.templateSettings = {
  19. 'interpolate': /{{([\s\S]+?)}}/g
  20. };
  21. _.template('hello {{ name }}!', { 'name': 'mustache' });
  22. // => 'hello mustache!'
  23. // using the `sourceURL` option to specify a custom sourceURL for the template
  24. var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
  25. compiled(data);
  26. // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
  27. // using the `variable` option to ensure a with-statement isn't used in the compiled template
  28. var compiled = _.template('hello <%= data.name %>!', null, { 'variable': 'data' });
  29. compiled.source;
  30. // => function(data) {
  31. var __t, __p = '', __e = _.escape;
  32. __p += 'hello ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
  33. return __p;
  34. }
  35. // using the `source` property to inline compiled templates for meaningful
  36. // line numbers in error messages and a stack trace
  37. fs.writeFileSync(path.join(cwd, 'jst.js'), '\
  38. var JST = {\
  39. "main": ' + _.template(mainText).source + '\
  40. };\
  41. ');

_.times(n, callback [, thisArg])

#

Executes the callback function n times, returning an array of the results of each callback execution. The callback is bound to thisArg and invoked with one argument; (index).

Arguments

  1. n (Number): The number of times to execute the callback.
  2. callback (Function): The function called per iteration.
  3. [thisArg] (Mixed): The this binding of callback.

Returns

(Array): Returns a new array of the results of each callback execution.

Example

  1. var diceRolls = _.times(3, _.partial(_.random, 1, 6));
  2. // => [3, 6, 4]
  3. _.times(3, function(n) { mage.castSpell(n); });
  4. // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
  5. _.times(3, function(n) { this.cast(n); }, mage);
  6. // => also calls `mage.castSpell(n)` three times

_.unescape(string)

#

The opposite of _.escape, this method converts the HTML entities &amp;, &lt;, &gt;, &quot;, and &#x27; in string to their corresponding characters.

Arguments

  1. string (String): The string to unescape.

Returns

(String): Returns the unescaped string.

Example

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

_.uniqueId([prefix])

#

Generates a unique id. If prefix is passed, the id will be appended to it.

Arguments

  1. [prefix] (String): The value to prefix the id with.

Returns

(Number, String): Returns a numeric id if no prefix is passed, else a string id may be returned.

Example

  1. _.uniqueId('contact_');
  2. // => 'contact_104'

Properties

_.VERSION

#

(String): The semantic version number.


_.templateSettings

#

(Object): By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby (ERB). Change the following template settings to use alternative delimiters.


_.templateSettings.escape

#

(RegExp): Used to detect data property values to be HTML-escaped.


_.templateSettings.evaluate

#

(RegExp): Used to detect code to be evaluated.


_.templateSettings.interpolate

#

(RegExp): Used to detect data property values to inject.


_.templateSettings.variable

#

(String): Used to reference the data object in the template text.