Lamb [logo]

A lightweight, and docile, JavaScript (ES5) library to help embracing functional programming.

Version:
  • 0.59.2
Author:
License:
  • MIT
Source:

Members

__ :Object Special properties

The placeholder object used in partial application.
Type:
Since:
  • 0.57.0
Source:
See:

Functions List

adapter(functions) → {function} Logic

Accepts a series of functions and builds a function that applies the received arguments to each one and returns the first non-undefined value.
Meant to work in synergy with casus and invoke, can be useful as a strategy pattern for functions, to mimic conditional logic or pattern matching, and also to build polymorphic functions.
Parameters:
Name Type Description
functions Array.<function()>
Since:
  • 0.6.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const filterString = _.compose(_.joinWith(""), _.filter);
const filterAdapter = _.adapter([
    _.invoke("filter"),
    _.casus(_.isType("String"), filterString)
]);

filterAdapter([1, 2, 3, 4, 5, 6], isEven) // => [2, 4, 6]
filterAdapter("123456", isEven) // => "246"
filterAdapter({}, isEven) // => undefined

// by its nature is composable
const filterWithDefault = _.adapter([filterAdapter, _.always("Not implemented")]);

filterWithDefault([1, 2, 3, 4, 5, 6], isEven) // => [2, 4, 6]
filterWithDefault("123456", isEven) // => "246"
filterWithDefault({}, isEven) // => "Not implemented"

add(a) → {function} Math

A curried version of sum.
Parameters:
Name Type Description
a Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const add5 = _.add(5);

_.add5(4) // => 9
_.add5(-2) // => 3

allOf(predicates) → {function} Logic

Accepts an array of predicates and builds a new one that returns true if they are all satisfied by the same arguments. The functions in the array will be applied one at a time until a false value is produced, which is returned immediately.
Parameters:
Name Type Description
predicates Array.<function()>
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const isPositiveEven = _.allOf([isEven, _.isGT(0)]);

isPositiveEven(-2) // => false
isPositiveEven(11) // => false
isPositiveEven(6) // => true

always(value) → {function} Function

Builds a function that returns a constant value. It's actually the simplest form of the K combinator or Kestrel.
Parameters:
Name Type Description
value *
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const truth = _.always(true);

truth() // => true
truth(false) // => true
truth(1, 2) // => true

// the value being returned is actually the
// very same value passed to the function
const foo = {bar: "baz"};
const alwaysFoo = _.always(foo);

alwaysFoo() === foo // => true

anyOf(predicates) → {function} Logic

Accepts an array of predicates and builds a new one that returns true if at least one of them is satisfied by the received arguments. The functions in the array will be applied one at a time until a true value is produced, which is returned immediately.
Parameters:
Name Type Description
predicates Array.<function()>
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const users = [
    {id: 1, name: "John", group: "guest"},
    {id: 2, name: "Jane", group: "root"},
    {id: 3, name: "Mario", group: "admin"}
];
const isInGroup = _.partial(_.hasKeyValue, ["group"]);
const isSuperUser = _.anyOf([isInGroup("admin"), isInGroup("root")]);

isSuperUser(users[0]) // => false
isSuperUser(users[1]) // => true
isSuperUser(users[2]) // => true

append(value) → {function} Array

A curried version of appendTo that uses the value to append to build a function expecting the array-like object to act upon.
Parameters:
Name Type Description
value *
Since:
  • 0.44.0
Source:
See:
Returns:

Type function

Example
const arr = [1, 2, 3, 4];

_.append(5)(arr) // => [1, 2, 3, 4, 5]
_.append([5])(arr) // => [1, 2, 3, 4, [5]]

appendTo(arrayLike, value) → {Array} Array

Appends the given value at the end of a copy of the provided array-like object.
Parameters:
Name Type Description
arrayLike ArrayLike
value *
Since:
  • 0.44.0
Source:
See:
Returns:

Type Array

Example
const arr = [1, 2, 3, 4];

_.appendTo(arr, 5) // => [1, 2, 3, 4, 5]
_.appendTo(arr, [5]) // => [1, 2, 3, 4, [5]]

application(fn, args) → {*} Function

Applies the given function to a list of arguments.
Parameters:
Name Type Description
fn function
args ArrayLike
Since:
  • 0.47.0
Source:
See:
Returns:

Type *

Example
_.application(_.sum, [3, 4]) // => 7

apply(fn) → {function} Function

A left-curried version of application. Expects the function to apply and builds a function waiting for the arguments array.
Parameters:
Name Type Description
fn function
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const arrayMax = _.apply(Math.max);

arrayMax([4, 5, 2, 6, 1]) // => 6

applyTo(args) → {function} Function

A right-curried version of application. Expects an array-like object to use as arguments and builds a function waiting for the target of the application.
Parameters:
Name Type Description
args ArrayLike
Since:
  • 0.47.0
Source:
See:
Returns:

Type function

Example
const data = [3, 4];
const applyToData = _.applyTo(data);

applyToData(_.sum) // => 7
applyToData(_.multiply) // => 12

areSame(a, b) → {Boolean} Logic

Verifies that the two supplied values are the same value using the "SameValue" comparison.
Note that this doesn't behave as the strict equality operator, but rather as a shim of ES6's Object.is. Differences are that 0 and -0 aren't the same value and, finally, NaN is equal to itself.
See also is for a curried version building a predicate and areSVZ and isSVZ to perform a "SameValueZero" comparison.
Parameters:
Name Type Description
a *
b *
Since:
  • 0.50.0
Source:
See:
Returns:

Type Boolean

Example
const testObject = {};

_.areSame({}, testObject) // => false
_.areSame(testObject, testObject) // => true
_.areSame("foo", "foo") // => true
_.areSame(0, -0) // => false
_.areSame(0 / 0, NaN) // => true

areSVZ(a, b) → {Boolean} Logic

Verifies that the two supplied values are the same value using the "SameValueZero" comparison.
With this comparison NaN is equal to itself, but 0 and -0 are considered the same value.
See also isSVZ for a curried version building a predicate and areSame and is to perform a "SameValue" comparison.
Parameters:
Name Type Description
a *
b *
Since:
  • 0.50.0
Source:
See:
Returns:

Type Boolean

Example
const testObject = {};

_.areSVZ({}, testObject) // => false
_.areSVZ(testObject, testObject) // => true
_.areSVZ("foo", "foo") // => true
_.areSVZ(0, -0) // => true
_.areSVZ(0 / 0, NaN) // => true

aritize(fn, arity) → {function} Function

Builds a new function that passes only the specified amount of arguments to the original one.
As slice is used to extract the arguments, you can also pass a negative arity.
Parameters:
Name Type Description
fn function
arity Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Examples
Math.max(10, 11, 45, 99) // => 99
_.aritize(Math.max, 2)(10, 11, 45, 99) // => 11

Using a negative arity:

_.aritize(Math.max, -1)(10, 11, 45, 99) // => 45

asPartial(fn) → {function} Function

Decorates the received function so that it can be called with placeholders to build a partial application of it.
The difference with partial is that, as long as you call the generated function with placeholders, another partial application of the original function will be built.
The final application will happen when one of the generated functions is invoked without placeholders, using the parameters collected so far.
This function comes in handy when you need to build different specialized functions starting from a basic one, but it's also useful when dealing with optional parameters as you can decide to apply the function even if its arity hasn't been entirely consumed.
Parameters:
Name Type Description
fn function
Since:
  • 0.36.0
Source:
See:
Returns:

Type function

Examples

Explaining the function's behaviour:

const __ = _.__;
const f = _.asPartial((a, b, c) => a + b + c);

f(4, 3, 2) // => 9
f(4, __, 2)(3) // => 9
f(__, 3, __)(4, __)(2) // => 9

Exploiting optional parameters:

const __ = _.__;
const f = _.asPartial((a, b, c) => a + b + (c || 0));

const addFive = f(5, __);
addFive(2) // => 7

const addNine = addFive(4, __);
addNine(11) // => 20

binary(fn) → {function} Function

Builds a function that passes only two arguments to the given function.
It's simply a shortcut for a common use case of aritize, exposed for convenience.
Parameters:
Name Type Description
fn function
Since:
  • 0.10.0
Source:
See:
Returns:

Type function

Example
_.list(1, 2, 3, 4, 5) // => [1, 2, 3, 4, 5]
_.binary(_.list)(1, 2, 3, 4, 5) // => [1, 2]

casus(predicate, fn) → {function} Logic

Builds a case for adapter.
The function will apply the received arguments to fn if the predicate is satisfied with the same arguments, otherwise will return undefined.
See also condition to build a condition with two branching functions and unless and when where one of the branches is the identity function.
Parameters:
Name Type Description
predicate function
fn function
Since:
  • 0.51.0
Source:
See:
Returns:

Type function

Example
const halveIfNumber = _.casus(_.isType("Number"), _.divideBy(2));

halveIfNumber(2) // => 1
halveIfNumber("2") // => undefined

checker(predicate, message, keyPaths, pathSeparatoropt) → {function} Object

Builds a checker function meant to be used with validate.
Note that the function accepts multiple keyPaths as a means to compare their values. In other words all the received keyPaths will be passed as arguments to the predicate to run the test.
If you want to run the same single property check with multiple properties, you should build multiple checkers and combine them with validate.
Parameters:
Name Type Attributes Default Description
predicate function The predicate to test the object properties
message String The error message
keyPaths Array.<String> The array of keys, or paths, to test.
pathSeparator String <optional>
"."
Since:
  • 0.1.0
Source:
See:
Returns:
A checker function which returns an error in the form ["message", ["propertyA", "propertyB"]] or an empty array.

Type function

Example
const user = {
    name: "John",
    surname: "Doe",
    login: {
        username: "jdoe",
        password: "abc123",
        passwordConfirm: "abc123"
    }
};
const pwdMatch = _.checker(
    _.areSame,
    "Passwords don't match",
    ["login.password", "login.passwordConfirm"]
);

pwdMatch(user) // => []

const newUser = _.setPathIn(user, "login.passwordConfirm", "avc123");

pwdMatch(newUser) // => ["Passwords don't match", ["login.password", "login.passwordConfirm"]]

clamp(n, min, max) → {Number} Math

"Clamps" a number within the given limits, both included.
The function will convert to number all its parameters before starting any evaluation, and will return NaN if min is greater than max.
Parameters:
Name Type Description
n Number
min Number
max Number
Since:
  • 0.13.0
Source:
See:
Returns:

Type Number

Example
_.clamp(-5, 0, 10) // => 0
_.clamp(5, 0, 10) // => 5
_.clamp(15, 0, 10) // => 10
_.clamp(0, 0, 10) // => 0
_.clamp(10, 0, 10) // => 10
_.is(_.clamp(-0, 0, 10), -0) // => true
_.clamp(10, 20, 15) // => NaN

clampWithin(min, max) → {function} Math

A curried version of clamp, expecting a min and a max value, that builds a function waiting for the number to clamp.
Parameters:
Name Type Description
min Number
max Number
Since:
  • 0.47.0
Source:
See:
Returns:

Type function

Example
_.clampWithin(0, 10)(-5) // => 0
_.clampWithin(0, 10)(5) // => 5
_.clampWithin(0, 10)(15) // => 10
_.clampWithin(0, 10)(0) // => 0
_.clampWithin(0, 10)(10) // => 10
_.is(_.clampWithin(0, 10)(-0), -0) // => true
_.clampWithin(20, 15)(10) // => NaN

collect(functions) → {function} Function

Accepts a series of functions and builds a new function. The functions in the series will then be applied, in order, with the values received by the function built with collect.
The collected results will be returned in an array.
Parameters:
Name Type Description
functions Array.<function()>
Since:
  • 0.35.0
Source:
Returns:

Type function

Examples
const user = {
    id: "jdoe",
    name: "John",
    surname: "Doe",
    scores: [2, 4, 7]
};
const getIDAndLastScore = _.collect([_.getKey("id"), _.getPath("scores.-1")]);

getIDAndLastScore(user) // => ["jdoe", 7]
const minAndMax = _.collect([Math.min, Math.max]);

minAndMax(3, 1, -2, 5, 4, -1) // => [-2, 5]

compose(a, b) → {function} Function

Returns a function that is the composition of the functions given as parameters. The first function consumes the result of the function that follows.
Parameters:
Name Type Description
a function
b function
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const sayHi = name => `Hi, ${name}`;
const capitalize = s => s[0].toUpperCase() + s.substr(1).toLowerCase();
const fixNameAndSayHi = _.compose(sayHi, capitalize);

sayHi("bOb") // => "Hi, bOb"
fixNameAndSayHi("bOb") // "Hi, Bob"

const users = [{name: "fred"}, {name: "bOb"}];
const sayHiToUser = _.compose(fixNameAndSayHi, _.getKey("name"));

_.map(users, sayHiToUser) // ["Hi, Fred", "Hi, Bob"]

condition(predicate, trueFn, falseFn) → {function} Logic

Builds a function that will apply the received arguments to trueFn, if the predicate is satisfied with the same arguments, or to falseFn otherwise.
Although you can use other conditions as trueFn or falseFn, it's probably better to use adapter to build more complex behaviours.
See also unless and when as they are shortcuts to common use cases.
Parameters:
Name Type Description
predicate function
trueFn function
falseFn function
Since:
  • 0.2.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const halveEvenAndDoubleOdd = _.condition(isEven, _.divideBy(2), _.multiplyBy(2));

halveEvenAndDoubleOdd(5) // => 10
halveEvenAndDoubleOdd(6) // => 3

contains(value) → {function} Array

Builds a predicate to check if an array-like object contains the given value.
Please note that the equality test is made with areSVZ; so you can check for NaN, but 0 and -0 are the same value.
See also isIn for an uncurried version.
Parameters:
Name Type Description
value *
Since:
  • 0.13.0
Source:
See:
Returns:

Type function

Example
const containsNaN = _.contains(NaN);

containsNaN([0, 1, 2, 3, NaN]) // => true

count(arrayLike, iteratee) → {Object} Array

Transforms an array-like object in a lookup table with the keys generated by the provided iteratee, having as values the count of matches for the key.
Parameters:
Name Type Description
arrayLike ArrayLike
iteratee ListIteratorCallback
Since:
  • 0.21.0
Source:
See:
Returns:

Type Object

Example
const persons = [
    {"name": "Jane", "age": 12},
    {"name": "John", "age": 40},
    {"name": "Mario", "age": 17},
    {"name": "Paolo", "age": 15}
];
const getAgeStatus = person => (person.age >= 18 ? "adult" : "minor");

_.count(persons, getAgeStatus) // => {"adult": 1, "minor": 3}

countBy(iteratee) → {function} Array

A curried version of count that uses the provided iteratee to build a function expecting the array-like object to act upon.
Parameters:
Name Type Description
iteratee ListIteratorCallback
Since:
  • 0.21.0
Source:
See:
Returns:

Type function

Example
const persons = [
    {"name": "Jane", "city": "New York"},
    {"name": "John", "city": "New York"},
    {"name": "Mario", "city": "Rome"},
    {"name": "Paolo"}
];
const getCityOrUnknown = _.adapter([_.getKey("city"), _.always("Unknown")]);
const countByCity = _.countBy(getCityOrUnknown);

countByCity(persons) // => {"New York": 2, "Rome": 1, "Unknown": 1}

curry(fn, arityopt) → {function} Function

Transforms the evaluation of the given function in the evaluation of a sequence of functions expecting only one argument. Each function of the sequence is a partial application of the original one, which will be applied when the specified (or derived) arity is consumed.
Currying will start from the leftmost argument: use curryRight for right currying.
Parameters:
Name Type Attributes Default Description
fn function
arity Number <optional>
fn.length
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const makeWithKeys = _.curry(_.make);
const makePerson = makeWithKeys(["name", "surname"]);

makePerson(["John", "Doe"]) // => {name: "John", surname: "Doe"};
makePerson(["Mario", "Rossi"]) // => {name: "Mario", surname: "Rossi"};

curryable(fn, arityopt) → {function} Function

Builds an auto-curried function. The resulting function can be called multiple times with any number of arguments, and the original function will be applied only when the specified (or derived) arity is consumed.
Currying will start from the leftmost argument: use curryableRight for right currying.
Parameters:
Name Type Attributes Default Description
fn function
arity Number <optional>
fn.length
Since:
  • 0.6.0
Source:
See:
Returns:

Type function

Example
const collectFourElements = _.curryable(_.list, 4);

collectFourElements(2)(3)(4)(5) // => [2, 3, 4, 5]
collectFourElements(2)(3, 4)(5) // => [2, 3, 4, 5]
collectFourElements(2, 3, 4, 5) // => [2, 3, 4, 5]
collectFourElements(2, 3)(4, 5) // => [2, 3, 4, 5]

curryableRight(fn, arityopt) → {function} Function

Same as curryable, but currying starts from the rightmost argument.
Parameters:
Name Type Attributes Default Description
fn function
arity Number <optional>
fn.length
Since:
  • 0.9.0
Source:
See:
Returns:

Type function

Example
const collectFourElements = _.curryableRight(_.list, 4);

collectFourElements(2)(3)(4)(5) // => [5, 4, 3, 2]
collectFourElements(2)(3, 4)(5) // => [5, 4, 3, 2]
collectFourElements(2, 3, 4, 5) // => [5, 4, 3, 2]
collectFourElements(2, 3)(4, 5) // => [5, 4, 3, 2]

curryRight(fn, arityopt) → {function} Function

Same as curry, but currying starts from the rightmost argument.
Parameters:
Name Type Attributes Default Description
fn function
arity Number <optional>
fn.length
Since:
  • 0.9.0
Source:
See:
Returns:

Type function

Example
const makeWithValues = _.curryRight(_.make);
const makeJohnDoe = makeWithValues(["John", "Doe"]);

makeJohnDoe(["name", "surname"]) // => {name: "John", surname: "Doe"};
makeJohnDoe(["firstName", "lastName"]) // => {firstName: "John", lastName: "Doe"};

debounce(fn, timespan) → {function} Function

Returns a function that will execute the given function only if it stops being called for the specified timespan.
See also throttle for a different behaviour where the first call happens immediately.
Parameters:
Name Type Description
fn function
timespan Number Expressed in milliseconds
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example

A common use case of debounce in a browser environment:

function updateLayout () {
    // some heavy DOM operations here
}

window.addEventListener("resize", _.debounce(updateLayout, 200), false);

// The resize event is fired repeteadly until the user stops resizing the
// window, while the `updateLayout` function is called only once: 200 ms
// after he stopped.

deduct(a) → {function} Math

A curried version of subtract that expects the subtrahend to build a function waiting for the minuend.
Parameters:
Name Type Description
a Number
Since:
  • 0.50.0
Source:
See:
Returns:

Type function

Example
const deduct5 = _.deduct(5);

deduct5(12) // => 7
deduct5(3) // => -2

difference(arrayLike, other) → {Array} Array

Returns an array of unique items present only in the first of the two given array-like objects. To determine uniqueness the function uses the "SameValueZero" comparison.
Parameters:
Name Type Description
arrayLike ArrayLike
other ArrayLike
Since:
  • 0.6.0
Source:
See:
Returns:

Type Array

Example
const a1 = [1, 2, 1, 3, 4];
const a2 = [2, 4, 5, 6];
const a3 = [3, 4, 5, 2, 1];

_.difference(a1, a2) // => [1, 3]
_.difference(a2, a3) // => [6]
_.difference(a1, a3) // => []

divide(a, b) → {Number} Math

Divides two numbers.
Parameters:
Name Type Description
a Number
b Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type Number

Example
_.divide(5, 2) // => 2.5

divideBy(a) → {function} Math

A curried version of divide that expects a divisor to build a function waiting for the dividend.
Parameters:
Name Type Description
a Number
Since:
  • 0.50.0
Source:
See:
Returns:

Type function

Example
const halve = divideBy(2);

halve(10) // => 5
halve(5) // => 2.5

drop(n) → {function} Array

A curried version of dropFrom that expects the number of elements to drop to build a function waiting for the list to take the elements from.
See the note and examples for dropFrom about passing a negative n.
Parameters:
Name Type Description
n Number
Since:
  • 0.5.0
Source:
See:
Returns:

Type function

Example
const drop2 = _.drop(2);

drop2([1, 2, 3, 4, 5]) // => [3, 4, 5]

dropFrom(arrayLike, n) → {Array} Array

Builds an array without the first n elements of the given array or array-like object. Note that, being this only a shortcut for a specific use case of slice, n can be a negative number.
Parameters:
Name Type Description
arrayLike ArrayLike
n Number
Since:
  • 0.51.0
Source:
See:
Returns:

Type Array

Example
const arr = [1, 2, 3, 4, 5];

_.dropFrom(arr, 2) // => [3, 4, 5]
_.dropFrom(arr, -1) // => [5]
_.dropFrom(arr, -10) // => [1, 2, 3, 4, 5]

dropLastWhile(predicate) → {function} Array

Builds a function that drops the last elements satisfying a predicate from an array or array-like object.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.58.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const dropLastWhileIsEven = _.dropLastWhile(isEven);

dropLastWhileIsEven([2, 4, 6, 8]) // => []
dropLastWhileIsEven([2, 4, 7, 8]) // => [2, 4, 7]

dropWhile(predicate) → {function} Array

Builds a function that drops the first elements satisfying a predicate from an array or array-like object.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.5.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const dropWhileIsEven = _.dropWhile(isEven);

dropWhileIsEven([2, 4, 6, 8]) // => []
dropWhileIsEven([2, 4, 7, 8]) // => [7, 8]

enumerables(obj) → {Array.<String>} Object

Creates an array with all the enumerable properties of the given object.
Parameters:
Name Type Description
obj Object
Since:
  • 0.12.0
Source:
See:
Returns:

Type Array.<String>

Example

Showing the difference with keys:

const baseFoo = Object.create({a: 1}, {b: {value: 2}});
const foo = Object.create(baseFoo, {
    c: {value: 3},
    d: {value: 4, enumerable: true}
});

_.keys(foo) // => ["d"]
_.enumerables(foo) // => ["d", "a"]

every(predicate) → {function} Array

A curried version of everyIn that expects a predicate to build a function waiting for the array-like to act upon.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.39.0
Source:
See:
Returns:

Type function

Example
const data = [2, 3, 5, 6, 8];
const isEven = n => n % 2 === 0;
const allEvens = _.every(isEven);
const allIntegers = _.every(_.isInteger);

allEvens(data) // => false
allIntegers(data) // => true

everyIn(arrayLike, predicate) → {Boolean} Array

Checks if all the elements in an array-like object satisfy the given predicate.
The function will stop calling the predicate as soon as it returns a falsy value.
Note that an empty array-like will always produce a true result regardless of the predicate because of vacuous truth.
Also note that unlike the native Array.prototype.every, this function won't skip deleted or unassigned indexes.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.39.0
Source:
See:
Returns:

Type Boolean

Examples
const persons = [
    {"name": "Jane", "age": 12, active: true},
    {"name": "John", "age": 40, active: true},
    {"name": "Mario", "age": 17, active: true},
    {"name": "Paolo", "age": 15, active: true}
];
const isAdult = _.keySatisfies(_.isGTE(18), "age");
const isActive = _.hasKeyValue("active", true);

_.everyIn(persons, isAdult) // => false
_.everyIn(persons, isActive) // => true

Showing the difference with Array.prototype.every:

const isDefined = _.not(_.isUndefined);
const arr = new Array(5);
arr[3] = 99;

arr.every(isDefined) // => true
_.everyIn(arr, isDefined) // => false

filter(arrayLike, predicate) → {Array} Array

Builds an array comprised of all values of the array-like object passing the predicate test.
Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example
const isLowerCase = s => s.toLowerCase() === s;

_.filter(["Foo", "bar", "baZ"], isLowerCase) // => ["bar"]

// the function will work with any array-like object
_.filter("fooBAR", isLowerCase) // => ["f", "o", "o"]

filterWith(predicate) → {function} Array

A curried version of filter that uses the given predicate to build a function expecting the array-like object to act upon.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.9.0
Source:
See:
Returns:

Type function

Example
const isLowerCase = s => s.toLowerCase() === s;
const getLowerCaseEntries = _.filterWith(isLowerCase);

getLowerCaseEntries(["Foo", "bar", "baZ"]) // => ["bar"]

// array-like objects can be used as well
getLowerCaseEntries("fooBAR") // => ["f", "o", "o"]

find(arrayLike, predicate) → {*} Array

Searches for an element satisfying the predicate in the given array-like object and returns it if the search is successful. Returns undefined otherwise.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.7.0
Source:
See:
Returns:

Type *

Example
const persons = [
    {"name": "Jane", "surname": "Doe", "age": 12},
    {"name": "John", "surname": "Doe", "age": 40},
    {"name": "Mario", "surname": "Rossi", "age": 18},
    {"name": "Paolo", "surname": "Bianchi", "age": 40}
];

_.find(persons, _.hasKeyValue("age", 40)) // => {"name": "John", "surname": "Doe", "age": 40}
_.find(persons, _.hasKeyValue("age", 41)) // => undefined

findIndex(arrayLike, predicate) → {Number} Array

Searches for an element satisfying the predicate in the given array-like object and returns its index if the search is successful. Returns -1 otherwise.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.7.0
Source:
See:
Returns:

Type Number

Example
const persons = [
    {"name": "Jane", "surname": "Doe", "age": 12},
    {"name": "John", "surname": "Doe", "age": 40},
    {"name": "Mario", "surname": "Rossi", "age": 18},
    {"name": "Paolo", "surname": "Bianchi", "age": 40}
];

_.findIndex(persons, _.hasKeyValue("age", 40)) // => 1
_.findIndex(persons, _.hasKeyValue("age", 41)) // => -1

findIndexWhere(predicate) → {function} Array

A curried version of findIndex that uses the given predicate to build a function expecting the array-like object to search.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.41.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const findEvenIdx = _.findIndexWhere(isEven);

findEvenIdx([1, 3, 4, 5, 6, 7]) // => 2
findEvenIdx([1, 3, 5, 7]) // => -1

findLast(arrayLike, predicate) → {*} Array

Searches for an element satisfying the predicate in the given array-like object starting from the end and returns it if the search is successful. Returns undefined otherwise.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.58.0
Source:
See:
Returns:

Type *

Example
const persons = [
    {"name": "Jane", "surname": "Doe", "age": 12},
    {"name": "John", "surname": "Doe", "age": 40},
    {"name": "Mario", "surname": "Rossi", "age": 18},
    {"name": "Paolo", "surname": "Bianchi", "age": 40}
];

_.findLast(persons, _.hasKeyValue("surname", "Doe")) // => {"name": "John", "surname": "Doe", "age": 40}
_.findLast(persons, _.hasKeyValue("age", 41)) // => undefined

findLastIndex(arrayLike, predicate) → {Number} Array

Searches for an element satisfying the predicate in the given array-like object starting from the end and returns its index if the search is successful. Returns -1 otherwise.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.58.0
Source:
See:
Returns:

Type Number

Example
const persons = [
    {"name": "Jane", "surname": "Doe", "age": 12},
    {"name": "John", "surname": "Doe", "age": 40},
    {"name": "Mario", "surname": "Rossi", "age": 18},
    {"name": "Paolo", "surname": "Bianchi", "age": 40}
];

_.findLastIndex(persons, _.hasKeyValue("age", 40)) // => 3
_.findLastIndex(persons, _.hasKeyValue("age", 41)) // => -1

findLastIndexWhere(predicate) → {function} Array

A curried version of findLastIndex that uses the given predicate to build a function expecting the array-like object to search.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.58.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const findLastEvenIdx = _.findLastIndexWhere(isEven);

findLastEvenIdx([1, 3, 4, 5, 6, 7]) // => 4
findLastEvenIdx([1, 3, 5, 7]) // => -1

findLastWhere(predicate) → {function} Array

A curried version of findLast that uses the given predicate to build a function expecting the array-like object to search.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.58.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const findEven = _.findLastWhere(isEven);

findEven([1, 3, 4, 5, 6, 7]) // => 6
findEven([1, 3, 5, 7]) // => undefined

findWhere(predicate) → {function} Array

A curried version of find that uses the given predicate to build a function expecting the array-like object to search.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.41.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const findEven = _.findWhere(isEven);

findEven([1, 3, 4, 5, 7]) // => 4
findEven([1, 3, 5, 7]) // => undefined

flatMap(array, iteratee) → {Array} Array

Similar to map, but if the mapping function returns an array this will be concatenated, rather than pushed, to the final result.
Parameters:
Name Type Description
array Array
iteratee ListIteratorCallback
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example

Showing the difference with map:

const words = ["foo", "bar"];
const toCharArray = _.splitBy("");

_.map(words, toCharArray) // => [["f", "o", "o"], ["b", "a", "r"]]
_.flatMap(words, toCharArray) // => ["f", "o", "o", "b", "a", "r"]

flatMapWith(iteratee) → {function} Array

A curried version of flatMap that uses provided iteratee to build a function expecting the array to act upon.
Parameters:
Name Type Description
iteratee ListIteratorCallback
Since:
  • 0.11.0
Source:
See:
Returns:

Type function

Example
const toCharArray = _.splitBy("");
const wordsToCharArray = _.flatMapWith(toCharArray);

wordsToCharArray(["foo", "bar"]) // => ["f", "o", "o", "b", "a", "r"]

flatten(array) → {Array} Array

Flattens an array.
Parameters:
Name Type Description
array Array
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example

Showing the difference with shallowFlatten:

const arr = [1, 2, [3, 4, [5, 6]], 7, 8];

_.flatten(arr) // => [1, 2, 3, 4, 5, 6, 7, 8]
_.shallowFlatten(arr) // => [1, 2, 3, 4, [5, 6], 7, 8]

flip(fn) → {function} Function

Returns a function that applies the original function with the arguments in reverse order.
Parameters:
Name Type Description
fn function
Since:
  • 0.1.0
Source:
Returns:

Type function

Example
_.list(1, 2, 3) // => [1, 2, 3]
_.flip(_.list)(1, 2, 3) // => [3, 2, 1]

forEach(arrayLike, iteratee) → {Undefined} Array

Executes the provided iteratee for each element of the given array-like object.
Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
Parameters:
Name Type Description
arrayLike ArrayLike
iteratee ListIteratorCallback
Since:
  • 0.1.0
Source:
Returns:

Type Undefined

Example

Adding a CSS class to all elements of a NodeList in a browser environment:

const addClass = _.curry(function (className, element) {
    element.classList.add(className);
});
const paragraphs = document.querySelectorAll("#some-container p");

_.forEach(paragraphs, addClass("main"));
// each "p" element in the container will have the "main" class now

fromPairs(pairsList) → {Object} Object

Builds an object from a list of key / value pairs like the one returned by pairs or ownPairs.
In case of duplicate keys the last key / value pair is used.
Parameters:
Name Type Description
pairsList Array.<Array.<String, *>>
Since:
  • 0.8.0
Source:
See:
Returns:

Type Object

Example
_.fromPairs([["a", 1], ["b", 2], ["c", 3]]) // => {"a": 1, "b": 2, "c": 3}
_.fromPairs([["a", 1], ["b", 2], ["a", 3]]) // => {"a": 3, "b": 2}
_.fromPairs([[1], [void 0, 2], [null, 3]]) // => {"1": undefined, "undefined": 2, "null": 3}

generate(start, len, iteratee) → {Array} Math

Generates a sequence of values of the desired length with the provided iteratee. The values being iterated, and received by the iteratee, are the results generated so far.
Parameters:
Name Type Description
start * The starting value
len Number The desired length for the sequence
iteratee ListIteratorCallback
Since:
  • 0.21.0
Source:
See:
Returns:

Type Array

Example
const fibonacci = (n, idx, results) => n + (results[idx - 1] || 0);

_.generate(1, 10, fibonacci) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

generic(method) → {function} Function

Creates generic functions out of methods.
Parameters:
Name Type Description
method function
Since:
  • 0.1.0
Author:
  • A very little change on a great idea by Irakli Gozalishvili. Thanks for this *beautiful* one-liner (never liked your "unbind" naming choice, though).
Source:
Returns:

Type function

Example
const join = _.generic(Array.prototype.join);

join([1, 2, 3, 4, 5], "-") // => "1-2-3-4-5"

// the function will work with any array-like object
join("hello", "-") // => "h-e-l-l-o"

getArgAt(idx) → {function} Function

Builds a function that returns the argument received at the given index.
As with getAt negative indexes are allowed.
The resulting function will return undefined if no arguments are passed or if the index is out of bounds.
Parameters:
Name Type Description
idx Number
Since:
  • 0.17.0
Source:
Returns:

Type function

Example
const getFirstArg = _.getArgAt(0);
const getLastArg = _.getArgAt(-1);

getFirstArg(1, 2, 3) // => 1
getLastArg(1, 2, 3) // => 3

_.getArgAt()(1, 2, 3) // => undefined
_.getArgAt(6)(1, 2, 3) // => undefined
_.getArgAt(1)() // => undefined

getAt(index) → {function} Array

A curried version of getIndex that uses the provided index to build a function expecting the array-like object holding the element we want to retrieve.
Parameters:
Name Type Description
index Number
Since:
  • 0.16.0
Source:
See:
Returns:

Type function

Examples
const getFifthElement = _.getAt(4);

getFifthElement([1, 2, 3, 4, 5]) // => 5
getFifthElement("foo bar") // => "b"
getFifthElement([]) // => undefined
getFifthElement("foo") // => undefined

Using negative indexes:

_.getAt(-2)([1, 2, 3]) // => 2
_.getAt(-3)("foo") // => "f"

getIn(obj, key) → {*} Object

Returns the value of the object property with the given key.
Parameters:
Name Type Description
obj Object
key String
Since:
  • 0.18.0
Source:
See:
Returns:

Type *

Example
const user = {name: "John"};

_.getIn(user, "name") // => "John";
_.getIn(user, "surname") // => undefined

getIndex(arrayLike, index) → {*} Array

Retrieves the element at the given index in an array-like object.
Like slice the index can be negative.
If the index isn't supplied, or if its value isn't an integer within the array-like bounds, the function will return undefined.
getIndex will throw an exception when receives null or undefined in place of an array-like object, but returns undefined for any other value.
Parameters:
Name Type Description
arrayLike ArrayLike
index Number
Since:
  • 0.23.0
Source:
See:
Returns:

Type *

Example
const arr = [1, 2, 3, 4, 5];

_.getIndex(arr, 1) // => 2
_.getIndex(arr, -1) // => 5

getKey(key) → {function} Object

A curried version of getIn.
Receives a property name and builds a function expecting the object from which we want to retrieve the property.
Parameters:
Name Type Description
key String
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const user1 = {name: "john"};
const user2 = {name: "jane"};
const getName = _.getKey("name");

getName(user1) // => "john"
getName(user2) // => "jane"

getPath(path, separatoropt) → {function} Object

Builds a partial application of getPathIn with the given path and separator, expecting the object to act upon.
Parameters:
Name Type Attributes Default Description
path String
separator String <optional>
"."
Since:
  • 0.19.0
Source:
See:
Returns:

Type function

Example
const user = {
    name: "John",
    surname: "Doe",
    login: {
        "user.name": "jdoe",
        password: "abc123"
    }
};

const getPwd = _.getPath("login.password");
const getUsername = _.getPath("login/user.name", "/");

getPwd(user) // => "abc123";
getUsername(user) // => "jdoe"

getPathIn(obj, path, separatoropt) → {*} Object

Gets a nested property value from an object using the given path.
The path is a string with property names separated by dots by default, but it can be customised with the optional third parameter.
You can use integers in the path, even negative ones, to refer to array-like object indexes, but the priority will be given to existing object keys: the last example explains this particular case.
Parameters:
Name Type Attributes Default Description
obj Object | ArrayLike
path String
separator String <optional>
"."
Since:
  • 0.19.0
Source:
See:
Returns:

Type *

Examples
const user = {
    name: "John",
    surname: "Doe",
    login: {
        "user.name": "jdoe",
        password: "abc123"
    },
    scores: [
        {id: 1, value: 10},
        {id: 2, value: 20},
        {id: 3, value: 30}
    ]
};

_.getPathIn(user, "name") // => "John"
_.getPathIn(user, "login.password") // => "abc123";
_.getPathIn(user, "login/user.name", "/") // => "jdoe"
_.getPathIn(user, "name.foo") // => undefined
_.getPathIn(user, "name.foo.bar") // => undefined

Accessing array-like objects indexes:

_.getPathIn(user, "login.password.1") // => "b"
_.getPathIn(user, "scores.0") // => {id: 1, value: 10}
_.getPathIn(user, "scores.-1.value") // => 30

Priority will be given to existing object keys over indexes:

_.getPathIn(user, "scores.-1") // => {id: 3, value: 30}

// let's do something funny
user.scores["-1"] = "foo bar";

_.getPathIn(user, "scores.-1") // => "foo bar";

group(arrayLike, iteratee) → {Object} Array

Transforms an array-like object into a lookup table using the provided iteratee as a grouping criterion to generate keys and values.
Parameters:
Name Type Description
arrayLike ArrayLike
iteratee ListIteratorCallback
Since:
  • 0.7.0
Source:
See:
Returns:

Type Object

Examples
const persons = [
    {"name": "Jane", "city": "New York"},
    {"name": "John", "city": "New York"},
    {"name": "Mario", "city": "Rome"},
    {"name": "Paolo"}
];
const getCity = _.getKey("city");
const personsByCity = _.group(persons, getCity);

// "personsByCity" holds:
// {
//     "New York": [
//         {"name": "Jane", "city": "New York"},
//         {"name": "John", "city": "New York"}
//     ],
//     "Rome": [
//         {"name": "Mario", "city": "Rome"}
//     ],
//     "undefined": [
//         {"name": "Paolo"}
//     ]
// }

Adding a custom value for missing keys:

const getCityOrUnknown = _.adapter([getCity, _.always("Unknown")]);

const personsByCity = _.group(persons, getCityOrUnknown);

// "personsByCity" holds:
// {
//     "New York": [
//         {"name": "Jane", "city": "New York"},
//         {"name": "John", "city": "New York"}
//     ],
//     "Rome": [
//         {"name": "Mario", "city": "Rome"}
//     ],
//     "Unknown": [
//         {"name": "Paolo"}
//     ]
// }

groupBy(iteratee) → {function} Array

A curried version of group that uses the provided iteratee to build a function expecting the array-like object to act upon.
Parameters:
Name Type Description
iteratee ListIteratorCallback
Since:
  • 0.7.0
Source:
See:
Returns:

Type function

Example
const persons = [
    {"name": "Jane", "age": 12},
    {"name": "John", "age": 40},
    {"name": "Mario", "age": 18},
    {"name": "Paolo", "age": 15}
];

const getAgeStatus = person => `${person.age > 20 ? "over" : "under"} 20`;
const groupByAgeStatus = _.groupBy(getAgeStatus);

const personsByAgeStatus = groupByAgeStatus(persons);

// "personsByAgeStatus" holds:
// {
//     "under 20": [
//         {"name": "Jane", "age": 12},
//         {"name": "Mario", "age": 18},
//         {"name": "Paolo", "age": 15}
//     ],
//     "over 20": [
//         {"name": "John", "age": 40}
//     ]
// }

gt(a, b) → {Boolean} Logic

Verifies that the first given value is greater than the second.
Wraps the native > operator within a function.
Parameters:
Name Type Description
a Number | String | Date | Boolean
b Number | String | Date | Boolean
Since:
  • 0.50.0
Source:
See:
Returns:

Type Boolean

Example
const pastDate = new Date(2010, 2, 12);
const today = new Date();

_.gt(today, pastDate) // => true
_.gt(pastDate, today) // => false
_.gt(3, 4) // => false
_.gt(3, 3) // => false
_.gt(3, 2) // => true
_.gt(0, -0) // => false
_.gt(-0, 0) // => false
_.gt("a", "A") // => true
_.gt("b", "a") // => true

gte(a, b) → {Boolean} Logic

Verifies that the first given value is greater than or equal to the second. Regarding equality, beware that this is simply a wrapper for the native >= operator, so -0 === 0.
Parameters:
Name Type Description
a Number | String | Date | Boolean
b Number | String | Date | Boolean
Since:
  • 0.50.0
Source:
See:
Returns:

Type Boolean

Example
_.gte(3, 4) // => false
_.gte(3, 3) // => true
_.gte(3, 2) // => true
_.gte(0, -0) // => true
_.gte(-0, 0) // => true

has(obj, key) → {Boolean} Object

Verifies the existence of a property in an object.
Parameters:
Name Type Description
obj Object
key String
Since:
  • 0.1.0
Source:
See:
Returns:

Type Boolean

Example
const user1 = {name: "john"};

_.has(user1, "name") // => true
_.has(user1, "surname") // => false
_.has(user1, "toString") // => true

const user2 = Object.create(null);

// not inherited through the prototype chain
_.has(user2, "toString") // => false

hasKey(key) → {function} Object

Curried version of has.
Returns a function expecting the object to check against the given key.
Parameters:
Name Type Description
key String
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const user1 = {name: "john"};
const user2 = {};
const hasName = _.hasKey("name");

hasName(user1) // => true
hasName(user2) // => false

hasKeyValue(key, value) → {function} Object

Builds a predicate expecting an object to check against the given key / value pair.
The value check is made with the "SameValueZero" comparison.
Parameters:
Name Type Description
key String
value *
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const hasTheCorrectAnswer = _.hasKeyValue("answer", 42);

hasTheCorrectAnswer({answer: 2}) // false
hasTheCorrectAnswer({answer: 42}) // true

hasOwn(obj, key) → {Boolean} Object

Verifies if an object has the specified property and that the property isn't inherited through the prototype chain.
Parameters:
Name Type Description
obj Object
key String
Since:
  • 0.1.0
Source:
See:
Returns:

Type Boolean

Example

Comparison with has:

const user = {name: "john"};

_.has(user, "name") // => true
_.has(user, "surname") // => false
_.has(user, "toString") // => true

_.hasOwn(user, "name") // => true
_.hasOwn(user, "surname") // => false
_.hasOwn(user, "toString") // => false

hasOwnKey(key) → {function} Object

Curried version of hasOwn.
Returns a function expecting the object to check against the given key.
Parameters:
Name Type Description
key String
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const user = {name: "john"};
const hasOwnName = _.hasOwnKey("name");
const hasOwnToString = _.hasOwnToString("toString");

hasOwnName(user) // => true
hasOwnToString(user) // => false

hasPathValue(path, value, separatoropt) → {function} Object

Builds a predicate to check if the given path exists in an object and holds the desired value.
The value check is made with the "SameValueZero" comparison.
Note that the function will check even non-enumerable properties.
Parameters:
Name Type Attributes Default Description
path String
value *
separator String <optional>
"."
Since:
  • 0.41.0
Source:
See:
Returns:

Type function

Example
const user = {
    name: "John",
    surname: "Doe",
    personal: {
        age: 25,
        gender: "M"
    },
    scores: [
        {id: 1, value: 10, passed: false},
        {id: 2, value: 20, passed: false},
        {id: 3, value: 30, passed: true}
    ]
};

const isMale = _.hasPathValue("personal.gender", "M");
const hasPassedFirstTest = _.hasPathValue("scores.0.passed", true);
const hasPassedLastTest = _.hasPathValue("scores.-1.passed", true);

isMale(user) // => true
hasPassedFirstTest(user) // => false
hasPassedLastTest(user) // => true
Retrieves the first element of an array-like object.
Just a common use case of getAt exposed for convenience.
Parameters:
Name Type Description
arrayLike ArrayLike
Since:
  • 0.16.0
Source:
See:
Returns:

Type *

Example
_.head([1, 2, 3]) // => 1
_.head("hello") // => "h"
_.head([]) // => undefined

identity(value) → {*} Function

The I combinator. Any value passed to the function is simply returned as it is.
Parameters:
Name Type Description
value *
Since:
  • 0.1.0
Source:
See:
Returns:
The value passed as parameter.

Type *

Example
const foo = {bar: "baz"};

_.identity(foo) === foo // true

index(arrayLike, iteratee) → {Object} Array

Similar to group, but the generated lookup table will have only one element of the original array-like object for each value.
Should be used only when you're sure that your iteratee won't produce duplicate keys, otherwise only the last evaluated element will be in the result.
Parameters:
Name Type Description
arrayLike ArrayLike
iteratee ListIteratorCallback
Since:
  • 0.21.0
Source:
See:
Returns:

Type Object

Examples
const users = [
    {id: 1, name: "John"},
    {id: 2, name: "Jane"},
    {id: 3, name: "Mario"},
    {id: 4, name: "John"}
];

const indexedUsers = _.index(users, _.getKey("id"));

// "indexedUsers" holds:
// {
//     "1": {id: 1, name: "John"},
//     "2": {id: 2, name: "Jane"},
//     "3": {id: 3, name: "Mario"},
//     "4": {id: 4, name: "John"}
// }

Result of an iteratee producing a duplicate key:

const users = [
    {id: 1, name: "John"},
    {id: 2, name: "Jane"},
    {id: 3, name: "Mario"},
    {id: 4, name: "John"}
];

const indexedUsers = _.index(users, _.getKey("name"));

// "indexedUsers" holds:
// {
//     "John": {"id": 4, "name": "John"},
//     "Jane": {"id": 2, "name": "Jane"},
//     "Mario": {"id": 3, "name": "Mario"}
// }

indexBy(iteratee) → {function} Array

A curried version of index that uses the provided iteratee to build a function expecting the array-like object to act upon.
Parameters:
Name Type Description
iteratee ListIteratorCallback
Since:
  • 0.21.0
Source:
See:
Returns:

Type function

Example
const users = [
    {id: 1, name: "John"},
    {id: 2, name: "Jane"},
    {id: 3, name: "Mario"}
];
const indexByID = _.indexBy(_.getKey("id"));

const indexedUsers = indexByID(users);

// "indexedUsers" holds:
// {
//     "1": {id: 1, name: "John"},
//     "2": {id: 2, name: "Jane"},
//     "3": {id: 3, name: "Mario"}
// }

init(arrayLike) → {Array} Array

Returns a copy of the given array-like object without the last element.
Parameters:
Name Type Description
arrayLike ArrayLike
Since:
  • 0.16.0
Source:
See:
Returns:

Type Array

Example
_.init([1, 2, 3, 4]) // => [1, 2, 3]
_.init([1]) // => []
_.init([]) // => []

insert(arrayLike, index, element) → {Array} Array

Inserts the provided element in a copy of an array-like object at the specified index.
If the index is greater than the length of the array-like, the element will be appended at the end.
Negative indexes are allowed; when a negative index is out of bounds the element will be inserted at the start of the resulting array.
Parameters:
Name Type Description
arrayLike ArrayLike
index Number
element *
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example
const arr = [1, 2, 3, 4, 5];

_.insert(arr, 3, 99) // => [1, 2, 3, 99, 4, 5]
_.insert(arr, -2, 99) // => [1, 2, 3, 99, 4, 5]
_.insert(arr, 10, 99) // => [1, 2, 3, 4, 5, 99]
_.insert(arr, -10, 99) // => [99, 1, 2, 3, 4, 5]

insertAt(index, element) → {function} Array

Builds a partial application of insert expecting the array-like object to act upon.
Parameters:
Name Type Description
index Number
element *
Since:
  • 0.27.0
Source:
See:
Returns:

Type function

Example
const arr = [1, 2, 3, 4, 5];

_.insertAt(3, 99)(arr) // => [1, 2, 3, 99, 4, 5]
_.insertAt(-2, 99)(arr) // => [1, 2, 3, 99, 4, 5]
_.insertAt(10, 99)(arr) // => [1, 2, 3, 4, 5, 99]
_.insertAt(-10, 99)(arr) // => [99, 1, 2, 3, 4, 5]

intersection(a, b) → {Array} Array

Returns an array of every unique item that is included in all two given arrays or array-like objects.
Note that this function uses the "SameValueZero" comparison.
Parameters:
Name Type Description
a ArrayLike
b ArrayLike
Since:
  • 0.5.0
Source:
See:
Returns:

Type Array

Example
const a1 = [1, 2, 3, 4];
const a2 = [2, 5, 4, 2, 6];
const a3 = [5, 6, 7];

_.intersection(a1, a2) // => [2, 4]
_.intersection(a2, a3) // => [5, 6]
_.intersection(a1, a3) // => []

invoke(methodName, boundArgsopt) → {function} Function

Builds a function that will invoke the given method name on any received object and return the result. If no method with such name is found the function will return undefined.
Along with the method name it's possible to supply some arguments that will be bound to the method call. Further arguments can also be passed when the function is actually called, and they will be concatenated to the bound ones.
Returning undefined is a behaviour meant to quickly create a case for adapter without the need to check for the existence of the desired method.
See also generic to create functions out of object methods.
Parameters:
Name Type Attributes Default Description
methodName String
boundArgs ArrayLike <optional>
[]
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Examples

Basic polymorphism with invoke:

const polySlice = _.invoke("slice");

polySlice([1, 2, 3, 4, 5], 1, 3) // => [2, 3]
polySlice("Hello world", 1, 3) // => "el"

With bound arguments:

const substrFrom2 = _.invoke("substr", [2]);

substrFrom2("Hello world") // => "llo world"
substrFrom2("Hello world", 5) // => "llo w"

invokeOn(target) → {function} Function

Accepts an object and builds a function expecting a method name, and optionally arguments, to call on such object. Like invoke, if no method with the given name is found the function will return undefined.
Parameters:
Name Type Description
target Object
Since:
  • 0.15.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const arr = [1, 2, 3, 4, 5];
const invokeOnArr = _.invokeOn(arr);

invokeOnArr("filter", isEven) // => [2, 4]
invokeOnArr("slice", 1, 3) // => [2, 3]

is(value) → {function} Logic

A curried version of areSame.
Accepts a value and builds a predicate that checks whether the value and the one received by the predicate are the same using the "SameValue" comparison.
See also areSVZ and isSVZ to perform a "SameValueZero" comparison.
Parameters:
Name Type Description
value *
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const john = {name: "John", surname: "Doe"};
const isJohn = _.is(john);
const isNegativeZero = _.is(-0);
const isReallyNaN = _.is(NaN);

isJohn(john) // => true
isJohn({name: "John", surname: "Doe"}) // => false

isNegativeZero(0) // => false
isNegativeZero(-0) // => true

isNaN(NaN) // => true
isNaN("foo") // => true

isReallyNaN(NaN) // => true
isReallyNaN("foo") // => false

isFinite(value) → {Boolean} Math

Verifies whether the received value is a finite number.
Behaves almost as a shim of ES6's Number.isFinite, but with a difference: it will return true even for Number object's instances.
Parameters:
Name Type Description
value *
Since:
  • 0.46.0
Source:
Returns:

Type Boolean

Example
_.isFinite(5) // => true
_.isFinite(new Number(5)) // => true
_.isFinite(Infinity) // => false
_.isFinite(-Infinity) // => false
_.isFinite("5") // => false
_.isFinite(NaN) // => false
_.isFinite(null) // => false

isGT(value) → {function} Logic

A right curried version of gt.
Accepts a value and builds a predicate that checks whether the value is greater than the one received by the predicate.
Parameters:
Name Type Description
value Number | String | Date | Boolean
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const isGreaterThan5 = _.isGT(5);

isGreaterThan5(3) // => false
isGreaterThan5(5) // => false
isGreaterThan5(7) // => true

isGTE(value) → {function} Logic

A right curried version of gte.
Accepts a value and builds a predicate that checks whether the value is greater than or equal to the one received by the predicate.
Parameters:
Name Type Description
value Number | String | Date | Boolean
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const isPositiveOrZero = _.isGTE(0);

isPositiveOrZero(-3) // => false
isPositiveOrZero(-0) // => true
isPositiveOrZero(0) // => true
isPositiveOrZero(5) // => true

isIn(arrayLike, value) → {Boolean} Array

Checks if an array-like object contains the given value.
Please note that the equality test is made with areSVZ; so you can check for NaN, but 0 and -0 are the same value.
See also contains for a curried version building a predicate.
Parameters:
Name Type Description
arrayLike ArrayLike
value *
Since:
  • 0.13.0
Source:
See:
Returns:

Type Boolean

Example
const numbers = [0, 1, 2, 3, NaN];

_.isIn(numbers, 1) // => true
_.isIn(numbers, 0) // => true
_.isIn(numbers, -0) // => true
_.isIn(numbers, NaN) // => true
_.isIn(numbers, 5) // => false

isInstanceOf(constructor) → {function} Type

Accepts a constructor and builds a predicate expecting an object, which will be tested to verify whether the prototype of the constructor is in its prototype chain.
Wraps in a convenient way the native instanceof operator.
Parameters:
Name Type Description
constructor *
Since:
  • 0.47.0
Source:
See:
Returns:

Type function

Example
function SomeObjA () {}

const a = new SomeObjA();
const sObj = new String("foo");
const s = "foo";

_.isInstanceOf(Object)(a) // => true
_.isInstanceOf(SomeObjA)(a) // => true

_.isInstanceOf(Object)(sObj) // => true
_.isInstanceOf(String)(sObj) // => true

_.isInstanceOf(Object)(s) // => false
_.isInstanceOf(String)(s) // => false

isInteger(value) → {Boolean} Math

Verifies whether the received value is a number and an integer. Behaves almost as a shim of ES6's Number.isInteger, but with a difference: it will return true even for Number object's instances.
Parameters:
Name Type Description
value *
Since:
  • 0.46.0
Source:
See:
Returns:

Type Boolean

Example
_.isInteger(5) // => true
_.isInteger(new Number(5)) // => true
_.isInteger(2.5) // => false
_.isInteger(Infinity) // => false
_.isInteger(-Infinity) // => false
_.isInteger("5") // => false
_.isInteger(NaN) // => false

isLT(value) → {function} Logic

A right curried version of lt.
Accepts a value and builds a predicate that checks whether the value is less than the one received by the predicate.
Parameters:
Name Type Description
value Number | String | Date | Boolean
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const isLessThan5 = _.isLT(5);

isLessThan5(7) // => false
isLessThan5(5) // => false
isLessThan5(3) // => true

isLTE(value) → {function} Logic

A right curried version of lte.
Accepts a value and builds a predicate that checks whether the value is less than or equal to the one received by the predicate.
Parameters:
Name Type Description
value Number | String | Date | Boolean
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const isNegativeOrZero = _.isLTE(0);

isNegativeOrZero(5) // => false
isNegativeOrZero(-0) // => true
isNegativeOrZero(0) // => true
isNegativeOrZero(-3) // => true

isNil(value) → {Boolean} Type

Verifies if a value is null or undefined.
Parameters:
Name Type Description
value *
Since:
  • 0.1.0
Source:
See:
Returns:

Type Boolean

Example
_.isNil(NaN) // => false
_.isNil({}) // => false
_.isNil(null) // => true
_.isNil(void 0) // => true
_.isNil() // => true

isNull(value) → {Boolean} Type

Verifies if a value is null.
Parameters:
Name Type Description
value *
Since:
  • 0.1.0
Source:
See:
  • isNil if you want to check for undefined too.
Returns:

Type Boolean

Example
_.isNull(null) // => true
_.isNull(void 0) // => false
_.isNull(false) // => false

isSafeInteger(value) → {Boolean} Math

Verifies whether the received value is a "safe integer", meaning that is a number and that can be exactly represented as an IEEE-754 double precision number. The safe integers consist of all integers from -(253 - 1) inclusive to 253 - 1 inclusive.
Behaves almost as a shim of ES6's Number.isSafeInteger, but with a difference: it will return true even for Number object's instances.
Parameters:
Name Type Description
value *
Since:
  • 0.46.0
Source:
See:
Returns:

Type Boolean

Example
_.isSafeInteger(5) // => true
_.isSafeInteger(new Number(5)) // => true
_.isSafeInteger(Math.pow(2, 53) - 1) // => true
_.isSafeInteger(Math.pow(2, 53)) // => false
_.isSafeInteger(2e32) // => false
_.isSafeInteger(2.5) // => false
_.isSafeInteger(Infinity) // => false
_.isSafeInteger(-Infinity) // => false
_.isSafeInteger("5") // => false
_.isSafeInteger(NaN) // => false

isSVZ(value) → {function} Logic

A curried version of areSVZ.
Accepts a value and builds a predicate that checks whether the value and the one received by the predicate are the same using the "SameValueZero" comparison.
See also areSame and is to perform a "SameValue" comparison.
Parameters:
Name Type Description
value *
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const john = {name: "John", surname: "Doe"};
const isJohn = _.isSVZ(john);
const isZero = _.isSVZ(0);
const isReallyNaN = _.isSVZ(NaN);

isJohn(john) // => true
isJohn({name: "John", surname: "Doe"}) // => false

isZero(0) // => true
isZero(-0) // => true

isNaN(NaN) // => true
isNaN("foo") // => true

isReallyNaN(NaN) // => true
isReallyNaN("foo") // => false

isType(typeName) → {function} Type

Builds a predicate that expects a value to check against the specified type.
Parameters:
Name Type Description
typeName String
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const isString = _.isType("String");

isString("Hello") // => true
isString(new String("Hi")) // => true

isUndefined(value) → {Boolean} Type

Verifies if a value is undefined.
Parameters:
Name Type Description
value *
Since:
  • 0.1.0
Source:
See:
  • isNil if you want to check for null too.
Returns:

Type Boolean

Example
_.isUndefined(null) // => false
_.isUndefined(void 0) // => true
_.isUndefined(false) // => false

join(arrayLike, separator) → {String} Array

Transforms an array-like object into a string by joining its elements with the given separator.
Note that unlike the native method, this function won't convert null and undefined values in the array to empty strings and that the separator parameter isn't optional.
See the examples about these differences.
Parameters:
Name Type Description
arrayLike ArrayLike
separator String
Since:
  • 0.58.0
Source:
See:
Returns:

Type String

Examples
const words = ["foo", "bar", "baz"];

_.join(words, "-") // => "foo-bar-baz"

Showing the differences with the native array method:

const mixed = [1, null, 2, undefined, 3, NaN, 4, 5];
const numbers = [1, 2, 3];

_.join(mixed, "-") // => "1-null-2-undefined-3-NaN-4-5"
mixed.join("-") // => "1--2--3-NaN-4-5"

_.join(numbers) // => "1undefined2undefined3"
numbers.join() // => "1,2,3"

joinWith(separator) → {function} Array

A curried version of join that accepts an optional separator and builds a function expecting the array-like object to act upon.
Please refer to the description and examples of join to understand the differences with the native array method.
Parameters:
Name Type Description
separator String
Since:
  • 0.58.0
Source:
See:
Returns:

Type function

Example
const words = ["foo", "bar", "baz"];
const joinWithDash = _.joinWith("-");

joinWithDash(words) // => "foo-bar-baz"

keys(obj) → {Array.<String>} Object

Retrieves the list of the own enumerable properties of an object.
Although Object.keys is already present in ECMAScript 5, its behaviour changed in the subsequent specifications of the standard.
This function shims the ECMAScript 6 version, by forcing a conversion to object for any value but null and undefined.
Parameters:
Name Type Description
obj Object
Since:
  • 0.25.1
Source:
See:
Returns:

Type Array.<String>

Example

Showing the difference with enumerables:

const baseFoo = Object.create({a: 1}, {b: {value: 2}});
const foo = Object.create(baseFoo, {
    c: {value: 3},
    d: {value: 4, enumerable: true}
});

_.enumerables(foo) // => ["d", "a"]
_.keys(foo) // => ["d"]

keySatisfies(predicate, key) → {function} Object

Builds a predicate to check if the given key satisfies the desired condition on an object.
Parameters:
Name Type Description
predicate function
key String
Since:
  • 0.45.0
Source:
See:
Returns:

Type function

Example
const users = [
    {name: "John", age: 25},
    {name: "Jane", age: 15},
];
const isAdult = _.keySatisfies(_.isGTE(18), "age");

isAdult(users[0]) // => true
isAdult(users[1]) // => false

last(arrayLike) → {*} Array

Retrieves the last element of an array-like object.
Just a common use case of getAt exposed for convenience.
Parameters:
Name Type Description
arrayLike ArrayLike
Since:
  • 0.16.0
Source:
See:
Returns:

Type *

Example
_.last([1, 2, 3]) // => 3
_.last("hello") // => "o"
_.last([]) // => undefined

list(…value) → {Array} Array

Generates an array with the values passed as arguments.
Behaves like ES6's Array.of.
Parameters:
Name Type Attributes Description
value * <repeatable>
Since:
  • 0.1.0
Source:
Returns:

Type Array

Example
_.list(1, 2, 3) // => [1, 2, 3]

lt(a, b) → {Boolean} Logic

Verifies that the first given value is less than the second.
Wraps the native < operator within a function.
Parameters:
Name Type Description
a Number | String | Date | Boolean
b Number | String | Date | Boolean
Since:
  • 0.50.0
Source:
See:
Returns:

Type Boolean

Example
const pastDate = new Date(2010, 2, 12);
const today = new Date();

_.lt(today, pastDate) // => false
_.lt(pastDate, today) // => true
_.lt(3, 4) // => true
_.lt(3, 3) // => false
_.lt(3, 2) // => false
_.lt(0, -0) // => false
_.lt(-0, 0) // => false
_.lt("a", "A") // => false
_.lt("a", "b") // => true

lte(a, b) → {Boolean} Logic

Verifies that the first given value is less than or equal to the second. Regarding equality, beware that this is simply a wrapper for the native <= operator, so -0 === 0.
Parameters:
Name Type Description
a Number | String | Date | Boolean
b Number | String | Date | Boolean
Since:
  • 0.50.0
Source:
See:
Returns:

Type Boolean

Example
_.lte(3, 4) // => true
_.lte(3, 3) // => true
_.lte(3, 2) // => false
_.lte(0, -0) // => true
_.lte(-0, 0) // => true

make(names, values) → {Object} Object

Builds an object from the two given lists, using the first one as keys and the last one as values.
If the list of keys is longer than the values one, the keys will be created with undefined values.
If more values than keys are supplied, the extra values will be ignored.
Parameters:
Name Type Description
names Array.<String>
values ArrayLike
Since:
  • 0.8.0
Source:
See:
Returns:

Type Object

Example
_.make(["a", "b", "c"], [1, 2, 3]) // => {a: 1, b: 2, c: 3}
_.make(["a", "b", "c"], [1, 2]) // => {a: 1, b: 2, c: undefined}
_.make(["a", "b"], [1, 2, 3]) // => {a: 1, b: 2}
_.make([null, void 0, 2], [1, 2, 3]) // => {"null": 1, "undefined": 2, "2": 3}

map(arrayLike, iteratee) → {Array} Array

Builds a new array by applying the iteratee function to each element of the received array-like object.
Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
Parameters:
Name Type Description
arrayLike ArrayLike
iteratee ListIteratorCallback
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example
_.map(["Joe", "Mario", "Jane"], _.invoke("toUpperCase")) // => ["JOE", "MARIO", "JANE"]

_.map([4, 9, 16], Math.sqrt); // => [2, 3, 4]

mapArgs(fn, mapper) → {function} Function

Builds a function that allows to map over the received arguments before applying them to the original one.
Parameters:
Name Type Description
fn function
mapper ListIteratorCallback
Since:
  • 0.3.0
Source:
See:
Returns:

Type function

Example
const sumArray = _.reduceWith(_.sum);
const sumArgs = _.compose(sumArray, _.list);

sumArgs(1, 2, 3, 4, 5) // => 15

const square = n => n ** 2;
const sumSquares = _.mapArgs(sumArgs, square);

sumSquares(1, 2, 3, 4, 5) // => 55

mapValues(source, fn) → {Object} Object

Creates a new object by applying the given function to all enumerable properties of the source one.
Parameters:
Name Type Description
source Object
fn ObjectIteratorCallback
Since:
  • 0.54.0
Source:
See:
Returns:

Type Object

Example
const weights = {
    john: "72.5 Kg",
    jane: "52.3 Kg"
};

_.mapValues(weights, parseFloat) // => {john: 72.5, jane: 52.3}

mapValuesWith(fn) → {function} Object

A curried version of mapValues.
Expects a mapping function to build a new function waiting for the object to act upon.
Parameters:
Name Type Description
fn ObjectIteratorCallback
Since:
  • 0.54.0
Source:
See:
Returns:

Type function

Example
const incValues = _.mapValuesWith(_.add(1));
const results = {
    first: 10,
    second: 5,
    third: 3
};

incValues(results) // => {first: 11, second: 6, third: 4}

mapWith(iteratee) → {function} Array

A curried version of map that uses the provided iteratee to build a function expecting the array-like object to act upon.
Parameters:
Name Type Description
iteratee ListIteratorCallback
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const square = n => n ** 2;
const getSquares = _.mapWith(square);

getSquares([1, 2, 3, 4, 5]) // => [1, 4, 9, 16, 25]

merge(a, b) → {Object} Object

Merges the enumerable properties of the provided sources into a new object.
In case of key homonymy the last source has precedence over the first.
Parameters:
Name Type Description
a Object
b Object
Since:
  • 0.10.0
Source:
See:
Returns:

Type Object

Examples
_.merge({a: 1, b: 3}, {b: 5, c: 4}) // => {a: 1, b: 5, c: 4}

Array-like objects will be transformed to objects with numbers as keys:

_.merge([1, 2], {a: 2}) // => {"0": 1, "1": 2, a: 2}
_.merge("foo", {a: 2}) // => {"0": "f", "1": "o", "2": "o", a: 2}

Every other non-nil value will be treated as an empty object:

_.merge({a: 2}, 99) // => {a: 2}
_.merge({a: 2}, NaN) // => {a: 2}

mergeOwn(a, b) → {Object} Object

Same as merge, but only the own properties of the sources are taken into account.
Parameters:
Name Type Description
a Object
b Object
Since:
  • 0.12.0
Source:
See:
  • merge to merge all enumerable properties
Returns:

Type Object

Examples

Showing the difference with merge:

const baseFoo = Object.create({a: 1}, {b: {value: 2, enumerable: true}, z: {value: 5}});
const foo = Object.create(baseFoo, {
    c: {value: 3, enumerable: true}
});

const bar = {d: 4};

_.merge(foo, bar) // => {a: 1, b: 2, c: 3, d: 4}
_.mergeOwn(foo, bar) // => {c: 3, d: 4}

Array-like objects will be transformed to objects with numbers as keys:

_.mergeOwn([1, 2], {a: 2}) // => {"0": 1, "1": 2, a: 2}
_.mergeOwn("foo", {a: 2}) // => {"0": "f", "1": "o", "2": "o", a: 2}

Every other non-nil value will be treated as an empty object:

_.mergeOwn({a: 2}, 99) // => {a: 2}
_.mergeOwn({a: 2}, NaN) // => {a: 2}

modulo(a, b) → {Number} Math

Performs the modulo operation and should not be confused with the remainder. The function performs a floored division to calculate the result and not a truncated one, hence the sign of the dividend is not kept, unlike the remainder.
Parameters:
Name Type Description
a Number
b Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type Number

Example
_.modulo(5, 3) // => 2
_.remainder(5, 3) // => 2

_.modulo(-5, 3) // => 1
_.remainder(-5, 3) // => -2

multiply(a, b) → {Number} Math

Multiplies two numbers.
Parameters:
Name Type Description
a Number
b Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type Number

Example
_.multiply(5, 3) // => 15

multiplyBy(a) → {function} Math

A curried version of multiply.
Parameters:
Name Type Description
a Number
Since:
  • 0.50.0
Source:
See:
Returns:

Type function

Example
const double = _.multiplyBy(2);

double(5) // => 10

not(predicate) → {function} Logic

Returns a predicate that negates the given one.
Parameters:
Name Type Description
predicate function
Since:
  • 0.1.0
Source:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const isOdd = _.not(isEven);

isOdd(5) // => true
isOdd(4) // => false

ownPairs(obj) → {Array.<Array.<String, *>>} Object

Same as pairs, but only the own enumerable properties of the object are taken into account.
See also fromPairs for the reverse operation.
Parameters:
Name Type Description
obj Object
Since:
  • 0.12.0
Source:
See:
Returns:

Type Array.<Array.<String, *>>

Example

Showing the difference with pairs:

const baseFoo = Object.create({a: 1}, {b: {value: 2, enumerable: true}, z: {value: 5}});
const foo = Object.create(baseFoo, {
    c: {value: 3, enumerable: true}
});

_.pairs(foo) // => [["c", 3], ["b", 2], ["a", 1]]
_.ownPairs(foo) // => [["c", 3]]

ownValues(obj) → {Array} Object

Same as values, but only the own enumerable properties of the object are taken into account.
Parameters:
Name Type Description
obj Object
Since:
  • 0.12.0
Source:
See:
Returns:

Type Array

Example

Showing the difference with values:

const baseFoo = Object.create({a: 1}, {b: {value: 2, enumerable: true}, z: {value: 5}});
const foo = Object.create(baseFoo, {
    c: {value: 3, enumerable: true}
});

_.values(foo) // => [3, 2, 1]
_.ownValues(foo) // => [3]

padLeft(source, char, len) → {String} String

Pads a string to the desired length with the given char starting from the beginning of the string.
Parameters:
Name Type Description
source String
char String The padding char. If a string is passed only the first char is used.
len Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type String

Example
_.padLeft("foo", "-", 0) // => "foo"
_.padLeft("foo", "-", -1) // => "foo"
_.padLeft("foo", "-", 5) // => "--foo"
_.padLeft("foo", "-", 3) // => "foo"
_.padLeft("foo", "ab", 7) // => "aaaafoo"
_.padLeft("foo", "", 5) // => "foo"
_.padLeft("", "-", 5) // => "-----"

padRight(source, char, len) → {String} String

Pads a string to the desired length with the given char starting from the end of the string.
Parameters:
Name Type Description
source String
char String The padding char. If a string is passed only the first char is used.
len Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type String

Example
_.padRight("foo", "-", 0) // => "foo"
_.padRight("foo", "-", -1) // => "foo"
_.padRight("foo", "-", 5) // => "foo--"
_.padRight("foo", "-", 3) // => "foo"
_.padRight("foo", "ab", 7) // => "fooaaaa"
_.padRight("foo", "", 5) // => "foo"
_.padRight("", "-", 5) // => "-----"

pairs(obj) → {Array.<Array.<String, *>>} Object

Converts an object into an array of key / value pairs of its enumerable properties.
See also ownPairs for picking only the own enumerable properties and fromPairs for the reverse operation.
Parameters:
Name Type Description
obj Object
Since:
  • 0.8.0
Source:
See:
Returns:

Type Array.<Array.<String, *>>

Example
_.pairs({a: 1, b: 2, c: 3}) // => [["a", 1], ["b", 2], ["c", 3]]

partial(fn, args) → {function} Function

Builds a partially applied function.
The __ object can be used as a placeholder for arguments.
Parameters:
Name Type Description
fn function
args Array
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const __ = _.__;
const users = [
    {id: 1, name: "John", active: true, confirmedMail: true},
    {id: 2, name: "Jane", active: true, confirmedMail: false},
    {id: 3, name: "Mario", active: false, confirmedMail: false}
];
const isKeyTrue = _.partial(_.hasKeyValue, [__, true]);
const isActive = isKeyTrue("active");
const hasConfirmedMail = isKeyTrue("confirmedMail");

_.map(users, isActive) // => [true, true, false]
_.map(users, hasConfirmedMail) // => [true, false, false]

partialRight(fn, args) → {function} Function

Like partial will build a partially applied function and it will accept placeholders.
The difference is that the bound arguments will be appended to the ones received by the resulting function.
Parameters:
Name Type Description
fn function
args Array
Since:
  • 0.52.0
Source:
See:
Returns:

Type function

Examples

Explaining the difference with partial:

const f1 = _.partial(_.list, ["a", "b", "c"]);
const f2 = _.partialRight(_.list, ["a", "b", "c"]);

f1("d", "e") // => ["a", "b", "c", "d", "e"]
f2("d", "e") // => ["d", "e", "a", "b", "c"]

Explaining placeholder substitutions:

const __ = _.__;
const f1 = _.partial(_.list, ["a", __, __, "d"]);
const f2 = _.partialRight(_.list, ["a", __, __, "d"]);

f1("b", "c", "e") // => ["a", "b", "c", "d", "e"]
f2("b", "c", "e") // => ["b", "a", "c", "e", "d"]

partition(arrayLike, predicate) → {Array.<Array, Array>} Array

Splits an array-like object in two lists: the first with the elements satisfying the given predicate, the others with the remaining elements.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.11.0
Source:
See:
Returns:

Type Array.<Array, Array>

Example
const isEven = n => n % 2 === 0;
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

_.partition(numbers, isEven) // => [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]

partitionWith(predicate) → {function} Array

A curried version of partition that uses the provided predicate to build a function expecting the array-like object to act upon.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.11.0
Source:
See:
Returns:

Type function

Example
const users = [
    {"name": "Jane", "surname": "Doe", "active": false},
    {"name": "John", "surname": "Doe", "active": true},
    {"name": "Mario", "surname": "Rossi", "active": true},
    {"name": "Paolo", "surname": "Bianchi", "active": false}
];
const isActive = _.hasKeyValue("active", true);
const splitByActiveStatus = _.partitionWith(isActive);

splitByActiveStatus(users) // =>
// [[
//     {"name": "John", "surname": "Doe", "active": true},
//     {"name": "Mario", "surname": "Rossi", "active": true}
// ], [
//     {"name": "Jane", "surname": "Doe", "active": false},
//     {"name": "Paolo", "surname": "Bianchi", "active": false}
// ]]

pathExists(path, separatoropt) → {function} Object

Builds a partial application of pathExistsIn using the given path and the optional separator. The resulting function expects the object to check.
Note that the function will check even non-enumerable properties.
Parameters:
Name Type Attributes Default Description
path String
separator String <optional>
"."
Since:
  • 0.43.0
Source:
See:
Returns:

Type function

Example
const user = {
    name: "John",
    surname: "Doe",
    address: {
        city: "New York"
    },
    scores: [10, 20, 15]
};

const hasCity = _.pathExists("address.city");
const hasCountry = _.pathExists("address.country");
const hasAtLeastThreeScores = _.pathExists("scores.2");

hasCity(user) // => true
hasCountry(user) // => false
hasAtLeastThreeScores(user) // => true

pathExistsIn(obj, path, separatoropt) → {Boolean} Object

Checks if the provided path exists in the given object.
Note that the function will check even non-enumerable properties.
Parameters:
Name Type Attributes Default Description
obj Object
path String
separator String <optional>
"."
Since:
  • 0.43.0
Source:
See:
Returns:

Type Boolean

Example
const user = {
    name: "John",
    surname: "Doe",
    address: {
        city: "New York"
    },
    scores: [10, 20, 15]
};

_.pathExistsIn(user, "address.city") // => true
_.pathExistsIn(user, "address.country") // => false
_.pathExistsIn(user, "scores.1") // => true

pathSatisfies(predicate, path, separatoropt) → {function} Object

Builds a predicate that verifies if a condition is satisfied for the given path in an object.
Like the other "path functions" you can use integers in the path, even negative ones, to refer to array-like object indexes, but the priority will be given to existing object keys.
Parameters:
Name Type Attributes Default Description
predicate function
path String
separator String <optional>
"."
Since:
  • 0.45.0
Source:
See:
Returns:

Type function

Example
const user = {
    name: "John",
    performance: {
        scores: [1, 5, 10]
    }
};

const gotAnHighScore = _.pathSatisfies(_.contains(10), "performance.scores");
const hadAGoodStart = _.pathSatisfies(_.isGT(6), "performance.scores.0");

gotAnHighScore(user) // => true
hadAGoodStart(user) // => false

pick(whitelist) → {function} Object

A curried version of pickIn, expecting a whitelist of keys to build a function waiting for the object to act upon.
Parameters:
Name Type Description
whitelist Array.<String>
Since:
  • 0.35.0
Source:
See:
Returns:

Type function

Examples
const user = {id: 1, name: "Jane", surname: "Doe", active: false};
const getUserInfo = _.pick(["id", "active"]);

getUserInfo(user) // => {id: 1, active: false}

A useful composition with mapWith:

const users = [
    {id: 1, name: "Jane", surname: "Doe", active: false},
    {id: 2, name: "John", surname: "Doe", active: true},
    {id: 3, name: "Mario", surname: "Rossi", active: true},
    {id: 4, name: "Paolo", surname: "Bianchi", active: false}
];
const select = _.compose(_.mapWith, _.pick);
const selectUserInfo = select(["id", "active"]);

selectUserInfo(users) // =>
// [
//     {id: 1, active: false},
//     {id: 2, active: true},
//     {id: 3, active: true},
//     {id: 4, active: false}
// ]

pickIf(predicate) → {function} Object

Builds a function expecting an object whose enumerable properties will be checked against the given predicate.
The properties satisfying the predicate will be included in the resulting object.
Parameters:
Name Type Description
predicate ObjectIteratorCallback
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const user = {name: "john", surname: "doe", age: 30};
const pickIfIsString = _.pickIf(_.isType("String"));

pickIfIsString(user) // => {name: "john", surname: "doe"}

pickIn(source, whitelist) → {Object} Object

Returns an object containing only the specified properties of the given object.
Non existent properties will be ignored.
Parameters:
Name Type Description
source Object
whitelist Array.<String>
Since:
  • 0.1.0
Source:
See:
Returns:

Type Object

Example
const user = {name: "john", surname: "doe", age: 30};

_.pickIn(user, ["name", "age"]) // => {"name": "john", "age": 30};
_.pickIn(user, ["name", "email"]) // => {"name": "john"}

pipe(functions) → {function} Function

Creates a pipeline of functions, where each function consumes the result of the previous one.
Parameters:
Name Type Description
functions Array.<function()>
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const square = n => n ** 2;
const getMaxAndSquare = _.pipe([Math.max, square]);

getMaxAndSquare(3, 5) // => 25

pluck(key) → {function} Array

A curried version of pluckFrom expecting the key to retrieve to build a function waiting for the array-like object to act upon.
Parameters:
Name Type Description
key String
Since:
  • 0.12.0
Source:
See:
Returns:

Type function

Example
const persons = [
    {"name": "Jane", "surname": "Doe", "age": 12},
    {"name": "John", "surname": "Doe", "age": 40},
    {"name": "Mario", "surname": "Rossi", "age": 18},
    {"name": "Paolo", "surname": "Bianchi", "age": 15}
];
const getAges = _.pluck("age");

getAges(persons) // => [12, 40, 18, 15]

pluckFrom(arrayLike, key) → {Array} Array

"Plucks" the values of the specified key from a list of objects.
Parameters:
Name Type Description
arrayLike ArrayLike
key String
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example
const persons = [
    {"name": "Jane", "surname": "Doe", "age": 12},
    {"name": "John", "surname": "Doe", "age": 40},
    {"name": "Mario", "surname": "Rossi", "age": 18},
    {"name": "Paolo", "surname": "Bianchi", "age": 15}
];

_.pluckFrom(persons, "age") // => [12, 40, 18, 15]

const lists = [
    [1, 2],
    [3, 4, 5],
    [6]
];

_.pluckFrom(lists, "length") // => [2, 3, 1]

pull(values) → {function} Array

A curried version of pullFrom expecting a list of values to build a function waiting for an array-like object.
The new function will create an array copy of the array-like without the specified values.
The equality test is made with the "SameValueZero" comparison.
See examples in pullFrom about the relationship with difference.
Parameters:
Name Type Description
values ArrayLike
Since:
  • 0.45.0
Source:
See:
Returns:

Type function

Example
const scores = [40, 20, 30, 10];
const newScores = [30, 10];
const pullNewScores = _.pull(newScores);

pullNewScores(scores) // => [40, 20]

pullFrom(arrayLike, values) → {Array} Array

Creates an array copy of the given array-like object without the specified values.
The equality test is made with the "SameValueZero" comparison.
Parameters:
Name Type Description
arrayLike ArrayLike
values ArrayLike
Since:
  • 0.45.0
Source:
See:
Returns:

Type Array

Examples
const arr = [1, 2, 3, 4, 5];

_.pullFrom(arr, [2, 5]) // => [1, 3, 4]

It's not the same as difference:

const arr = [1,1,2,3,4,4,5];

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

randomInt(min, max) → {Number} Math

Generates a random integer between two given integers, both included. Note that no safety measure is taken if the provided arguments aren't integers, so you may end up with unexpected (not really) results. For example randomInt(0.1, 1.2) could be 2.
Parameters:
Name Type Description
min Number
max Number
Since:
  • 0.1.0
Source:
Returns:

Type Number

Example
_.randomInt(1, 10) // => an integer >=1 && <= 10

range(start, limit, stepopt) → {Array.<Number>} Math

Generates an arithmetic progression of numbers starting from start up to, but not including, limit, using the given step.
Parameters:
Name Type Attributes Default Description
start Number
limit Number
step Number <optional>
1
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array.<Number>

Examples
_.range(2, 10) // => [2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, -10, -2) // => [1, -1, -3, -5, -7, -9]
_.range(0, 3, 1) // => [0, 1, 2]
_.range(-0, 3, 1) // => [-0, 1, 2]
_.range(1, -10, 2) // => []
_.range(3, 5, -1) // => []

Behaviour if step happens to be zero:

_.range(2, 10, 0) // => [2]
_.range(2, -10, 0) // => [2]
_.range(2, 2, 0) // => []

reduce(arrayLike, accumulator, initialValueopt) → {*} Array

Reduces (or folds) the values of an array-like object, starting from the first, to a new value using the provided accumulator function.
Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
Parameters:
Name Type Attributes Description
arrayLike ArrayLike
accumulator AccumulatorCallback
initialValue * <optional>
Since:
  • 0.1.0
Source:
See:
Returns:

Type *

Example
_.reduce([1, 2, 3, 4], _.sum) // => 10

reduceRight(arrayLike, accumulator, initialValueopt) → {*} Array

Same as reduce, but starts the fold operation from the last element instead.
Note that unlike the native array method this function doesn't skip unassigned or deleted indexes.
Parameters:
Name Type Attributes Description
arrayLike ArrayLike
accumulator AccumulatorCallback
initialValue * <optional>
Since:
  • 0.1.0
Source:
See:
Returns:

Type *

reduceRightWith(accumulator, initialValueopt) → {function} Array

A partial application of reduceRight that uses the provided accumulator and the optional initialValue to build a function expecting the array-like object to act upon.
Parameters:
Name Type Attributes Description
accumulator AccumulatorCallback
initialValue * <optional>
Since:
  • 0.27.0
Source:
See:
Returns:

Type function

Example
const arr = [1, 2, 3, 4, 5];

_.reduceRightWith(_.sum)(arr) // => 15
_.reduceRightWith(_.subtract)(arr) // => -5
_.reduceRightWith(_.subtract, 0)(arr) // => -15

reduceWith(accumulator, initialValueopt) → {function} Array

A partial application of reduce that uses the provided accumulator and the optional initialValue to build a function expecting the array-like object to act upon.
Parameters:
Name Type Attributes Description
accumulator AccumulatorCallback
initialValue * <optional>
Since:
  • 0.27.0
Source:
See:
Returns:

Type function

Example
const arr = [1, 2, 3, 4, 5];

_.reduceWith(_.sum)(arr) // => 15
_.reduceWith(_.subtract)(arr) // => -13
_.reduceWith(_.subtract, 0)(arr) // => -15

remainder(a, b) → {Number} Math

Gets the remainder of the division of two numbers. Not to be confused with the modulo as the remainder keeps the sign of the dividend and may lead to some unexpected results.
Parameters:
Name Type Description
a Number
b Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type Number

Example
// example of wrong usage of the remainder
// (in this case the modulo operation should be used)
const isOdd = n => _.remainder(n, 2) === 1;

isOdd(-3) // => false as -3 % 2 === -1

rename(keysMap) → {function} Object

A curried version of renameIn expecting a keysMap to build a function waiting for the object to act upon.
Parameters:
Name Type Description
keysMap Object
Since:
  • 0.26.0
Source:
See:
Returns:

Type function

Example
const persons = [
    {"firstName": "John", "lastName": "Doe"},
    {"first_name": "Mario", "last_name": "Rossi"},
];
const normalizeKeys = _.rename({
    "firstName": "name",
    "first_name": "name",
    "lastName": "surname",
    "last_name": "surname"
});

_.map(persons, normalizeKeys) // =>
// [
//     {"name": "John", "surname": "Doe"},
//     {"name": "Mario", "surname": "Rossi"}
// ]

renameIn(source, keysMap) → {Object} Object

Creates a copy of the given object with its enumerable keys renamed as indicated in the provided lookup table.
Parameters:
Name Type Description
source Object
keysMap Object
Since:
  • 0.26.0
Source:
See:
Returns:

Type Object

Examples
const person = {"firstName": "John", "lastName": "Doe"};
const keysMap = {"firstName": "name", "lastName": "surname"};

_.renameIn(person, keysMap) // => {"name": "John", "surname": "Doe"}

It's safe using it to swap keys:

const keysMap = {"firstName": "lastName", "lastName": "firstName"};

_.renameIn(person, keysMap) // => {"lastName": "John", "firstName": "Doe"}

renameWith(fn) → {function} Object

Uses the provided function as a keysMap generator and returns a function expecting the object whose keys we want to renameIn.
Parameters:
Name Type Description
fn function
Since:
  • 0.26.0
Source:
See:
Returns:

Type function

Example
const person = {"NAME": "John", "SURNAME": "Doe"};
const arrayToLower = _.mapWith(_.invoke("toLowerCase"));
const makeLowerKeysMap = function (source) {
    const sourceKeys = _.keys(source);

    return _.make(sourceKeys, arrayToLower(sourceKeys));
};
const lowerKeysFor = _.renameWith(makeLowerKeysMap);

lowerKeysFor(person) // => {"name": "John", "surname": "doe"};

repeat(source, times) → {String} String

Builds a new string by repeating the source string the desired amount of times.
Note that unlike the current ES6 proposal for String.prototype.repeat, this function doesn't throw a RangeError if times is negative, but returns an empty string instead.
Parameters:
Name Type Description
source String
times Number
Since:
  • 0.1.0
Source:
Returns:

Type String

Example
_.repeat("Hello", -1) // => ""
_.repeat("Hello", 1) // => "Hello"
_.repeat("Hello", 3) // => "HelloHelloHello"

reverse(arrayLike) → {Array} Array

Reverses a copy of the given array-like object.
Parameters:
Name Type Description
arrayLike ArrayLike
Since:
  • 0.19.0
Source:
Returns:

Type Array

Example
const arr = [1, 2, 3];

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

// `arr` still is [1, 2, 3]

rotate(arrayLike, amount) → {Array} Array

Returns a copy of the given array-like with the element rotated by the desired amount. Negative indexes are allowed.
Parameters:
Name Type Description
arrayLike ArrayLike
amount Number
Since:
  • 0.55.0
Source:
See:
Returns:

Type Array

Example
const arr = [1, 2, 3, 4, 5];

_.rotate(arr, 3) // => [3, 4, 5, 1, 2]
_.rotate(arr, -3) // => [4, 5, 1, 2, 3]
_.rotate(arr, 11) // => [5, 1, 2, 3, 4]

rotateBy(amount) → {function} Array

A curried version of rotate.
Uses the given amount to build a function expecting the array to rotate by that amount.
Parameters:
Name Type Description
amount Number
Since:
  • 0.55.0
Source:
See:
Returns:

Type function

Example
const arr = [1, 2, 3, 4, 5];
const rotateByTwo = _.rotateBy(2);

rotateByTwo(arr) // => [4, 5, 1, 2, 3]

setAt(index, value) → {function} Array

A curried version of setIndex that builds a function that creates a copy of an array-like object with the given index changed to the desired value.
If the index is not an integer or if it's out of bounds, the function will return a copy of the original array.
Negative indexes are allowed.
Parameters:
Name Type Description
index Number
value *
Since:
  • 0.17.0
Source:
See:
Returns:

Type function

Examples
const arr = [1, 2, 3, 4, 5];

_.setAt(2, 99)(arr) // => [1, 2, 99, 4, 5]
arr // => [1, 2, 3, 4, 5]

_.setAt(10, 99)(arr) // => [1, 2, 3, 4, 5] (not a reference to `arr`)

Using negative indexes:

_.setAt(-1, 99)(arr) // => [1, 2, 3, 4, 99]

setIn(source, key, value) → {Object} Object

Sets the specified key to the given value in a copy of the provided object.
All the remaining enumerable keys of the source object will be simply copied in the result object without breaking references.
If the specified key is not part of the source object, it will be added to the result.
The main purpose of the function is to work on simple plain objects used as data structures, such as JSON objects, and makes no effort to play nice with objects created from an OOP perspective (it's not worth it).
For example the prototype of the result will be Object's regardless of the source's one.
Parameters:
Name Type Description
source Object
key String
value *
Since:
  • 0.18.0
Source:
See:
Returns:

Type Object

Example
const user = {name: "John", surname: "Doe", age: 30};

_.setIn(user, "name", "Jane") // => {name: "Jane", surname: "Doe", age: 30}
_.setIn(user, "gender", "male") // => {name: "John", surname: "Doe", age: 30, gender: "male"}

// `user` still is {name: "John", surname: "Doe", age: 30}

setIndex(arrayLike, index, value) → {Array} Array

Creates a copy of an array-like object with the given index changed to the desired value.
If the index is not an integer or if it's out of bounds, the function will return a copy of the original array.
Negative indexes are allowed.
Parameters:
Name Type Description
arrayLike ArrayLike
index Number
value *
Since:
  • 0.23.0
Source:
See:
Returns:

Type Array

Example
const arr = [1, 2, 3];

_.setIndex(arr, 1, 99) // => [1, 99, 3]
_.setIndex(arr, -1, 99) // => [1, 2, 99]
_.setIndex(arr, 10, 99) // => [1, 2, 3] (not a reference to `arr`)

setKey(key, value) → {function} Object

Builds a partial application of setIn with the provided key and value.
The resulting function expects the object to act upon.
Please refer to setIn's description for explanations about how the copy of the source object is made.
Parameters:
Name Type Description
key String
value *
Since:
  • 0.18.0
Source:
See:
Returns:

Type function

Example
const user = {name: "John", surname: "Doe", age: 30};
const setAgeTo40 = _.setKey("age", 40);

setAgeTo40(user) // => {name: "john", surname: "doe", age: 40}

// `user` still is {name: "John", surname: "Doe", age: 30}

setPath(path, value, separatoropt) → {function} Object

Builds a partial application of setPathIn expecting the object to act upon.
See setPathIn for more details and examples.
Parameters:
Name Type Attributes Default Description
path String
value *
separator String <optional>
"."
Since:
  • 0.20.0
Source:
See:
Returns:

Type function

Example
const user = {id: 1, status: {active: false}};
const activate = _.setPath("status.active", true);

activate(user) // => {id: 1, status: {active: true}}

setPathIn(source, path, value, separatoropt) → {Object|Array} Object

Allows to change a nested value in a copy of the provided object.
The function will delegate the "set action" to setIn or setAt depending on the value encountered in the path, so please refer to the documentation of those functions for specifics about the implementation.
Note anyway that the distinction will be between Arrays, delegated to setAt, and everything else (including array-like objects), which will be delegated to setIn.
As a result of that, array-like objects will be converted to objects having numbers as keys and paths targeting non-object values will be converted to empty objects.
You can anyway target array elements using integers in the path, even negative ones, but the priority will be given to existing, and enumerable, object keys.
Non-enumerable properties encountered in the path will be considered as non-existent properties.
Like getPathIn or getPath you can use custom path separators.
Parameters:
Name Type Attributes Default Description
source Object | Array
path String
value *
separator String <optional>
"."
Since:
  • 0.20.0
Source:
See:
Returns:

Type Object | Array

Examples
const user = {id: 1, status: {active : false, scores: [2, 4, 6]}};

_.setPathIn(user, "status.active", true) // => {id: 1, status: {active : true, scores: [2, 4, 6]}}

Targeting arrays:

_.setPathIn(user, "status.scores.0", 8) // => {id: 1, status: {active : false, scores: [8, 4, 6]}}

// you can use negative indexes as well
_.setPathIn(user, "status.scores.-1", 8) // => {id: 1, status: {active : false, scores: [2, 4, 8]}}

Arrays can also be part of the path and not necessarily its target:

const user = {
    id: 1,
    scores: [
        {value: 2, year: "2000"},
        {value: 4, year: "2001"},
        {value: 6, year: "2002"}
    ]
};

const newUser = _.setPathIn(user, "scores.0.value", 8);
// "newUser" holds:
// {
//     id: 1,
//     scores: [
//         {value: 8, year: "2000"},
//         {value: 4, year: "2001"},
//         {value: 6, year: "2002"}
//     ]
// }

shallowFlatten(array) → {Array} Array

Flattens the "first level" of an array.
Parameters:
Name Type Description
array Array
Since:
  • 0.9.0
Source:
See:
Returns:

Type Array

Example

Showing the difference with flatten:

const arr = [1, 2, [3, 4, [5, 6]], 7, 8];

_.flatten(arr) // => [1, 2, 3, 4, 5, 6, 7, 8]
_.shallowFlatten(arr) // => [1, 2, 3, 4, [5, 6], 7, 8]

skip(blacklist) → {function} Object

A curried version of skipIn, expecting a blacklist of keys to build a function waiting for the object to act upon.
Parameters:
Name Type Description
blacklist Array.<String>
Since:
  • 0.35.0
Source:
See:
Returns:

Type function

Examples
const user = {id: 1, name: "Jane", surname: "Doe", active: false};
const getUserInfo = _.skip(["name", "surname"]);

getUserInfo(user) // => {id: 1, active: false}

A useful composition with mapWith:

const users = [
    {id: 1, name: "Jane", surname: "Doe", active: false},
    {id: 2, name: "John", surname: "Doe", active: true},
    {id: 3, name: "Mario", surname: "Rossi", active: true},
    {id: 4, name: "Paolo", surname: "Bianchi", active: false}
];
const discard = _.compose(_.mapWith, _.skip);
const discardNames = discard(["name", "surname"]);

discardNames(users) // =>
// [
//     {id: 1, active: false},
//     {id: 2, active: true},
//     {id: 3, active: true},
//     {id: 4, active: false}
// ]

skipIf(predicate) → {function} Object

Builds a function expecting an object whose enumerable properties will be checked against the given predicate.
The properties satisfying the predicate will be omitted in the resulting object.
Parameters:
Name Type Description
predicate ObjectIteratorCallback
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const user = {name: "john", surname: "doe", age: 30};
const skipIfIstring = _.skipIf(_.isType("String"));

skipIfIstring(user) // => {age: 30}

skipIn(source, blacklist) → {Object} Object

Returns a copy of the source object without the specified properties.
Parameters:
Name Type Description
source Object
blacklist Array.<String>
Since:
  • 0.1.0
Source:
See:
Returns:

Type Object

Example
const user = {name: "john", surname: "doe", age: 30};

_.skipIn(user, ["name", "age"]) // => {surname: "doe"};
_.skipIn(user, ["name", "email"]) // => {surname: "doe", age: 30};

slice(arrayLike, start, end) → {Array} Array

Builds an array by extracting a portion of an array-like object.
Note that unlike the native array method this function ensures that dense arrays are returned.
Also, unlike the native method, the start and end parameters aren't optional and will be simply converted to integer.
See dropFrom and drop if you want a slice to the end of the array-like.
Parameters:
Name Type Description
arrayLike ArrayLike Any array like object.
start Number Index at which to begin extraction.
end Number Index at which to end extraction. Extracts up to but not including end.
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example
const arr = [1, 2, 3, 4, 5];

_.slice(arr, 0, 2) // => [1, 2]
_.slice(arr, 2, -1) // => [3, 4]
_.slice(arr, -3, 5) // => [3, 4, 5]

sliceAt(start, end) → {function} Array

Given the start and end bounds, builds a partial application of slice expecting the array-like object to slice.
See also dropFrom and drop if you want a slice to the end of the array-like.
Parameters:
Name Type Description
start Number Index at which to begin extraction.
end Number Index at which to end extraction. Extracts up to but not including end.
Since:
  • 0.48.0
Source:
See:
Returns:

Type function

Example
const arr = [1, 2, 3, 4, 5];
const s = "hello";
const dropFirstAndLast = _.sliceAt(1, -1);

dropFirstAndLast(arr) // => [2, 3, 4]
dropFirstAndLast(s) // => ["e", "l", "l"]

some(predicate) → {function} Array

A curried version of someIn that uses the given predicate to build a function waiting for the array-like to act upon.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.39.0
Source:
See:
Returns:

Type function

Example
const data = [1, 3, 5, 6, 7, 8];
const isEven = n => n % 2 === 0;
const containsEvens = _.some(isEven);
const containsStrings = _.some(_.isType("String"));

containsEvens(data) // => true
containsStrings(data) // => false

someIn(arrayLike, predicate) → {Boolean} Array

Checks if at least one element in an array-like object satisfies the given predicate.
The function will stop calling the predicate as soon as it returns a truthy value.
Note that unlike the native Array.prototype.some, this function won't skip deleted or unassigned indexes.
Parameters:
Name Type Description
arrayLike ArrayLike
predicate ListIteratorCallback
Since:
  • 0.39.0
Source:
See:
Returns:

Type Boolean

Examples
const persons = [
    {"name": "Jane", "age": 12, active: false},
    {"name": "John", "age": 40, active: false},
    {"name": "Mario", "age": 17, active: false},
    {"name": "Paolo", "age": 15, active: false}
];
const isAdult = _.keySatisfies(_.isGTE(18), "age");
const isActive = _.hasKeyValue("active", true);

_.someIn(persons, isAdult) // => true
_.someIn(persons, isActive) // => false

Showing the difference with Array.prototype.some:

const arr = new Array(5);
arr[3] = 99;

arr.some(_.isUndefined) // => false
_.someIn(arr, _.isUndefined) // => true

sort(arrayLike, sortersopt) → {Array} Array

Returns a stably sorted copy of an array-like object using the given criteria.
Sorting criteria are built using Lamb's sorter function, but you can also pass simple "reader" functions and default ascending sorters will be built for you.
A "reader" is a function that evaluates the array element and supplies the value to be used in the comparison.
Please note that if the arguments received by the default comparer aren't of the same type, they will be compared as strings.
Parameters:
Name Type Attributes Default Description
arrayLike ArrayLike
sorters Array.<Sorter> | Array.<function()> <optional>
[sorter()]
Since:
  • 0.15.0
Source:
See:
Returns:

Type Array

Examples

Stable sort:

const persons = [
    {"name": "John", "surname" :"Doe"},
    {"name": "Mario", "surname": "Rossi"},
    {"name": "John", "surname" :"Moe"},
    {"name": "Jane", "surname": "Foe"}
];

const personsByName = _.sort(persons, [_.getKey("name")]);

// personsByName holds:
// [
//     {"name": "Jane", "surname": "Foe"},
//     {"name": "John", "surname" :"Doe"},
//     {"name": "John", "surname" :"Moe"},
//     {"name": "Mario", "surname": "Rossi"}
// ]

Stable multi-sort:

const personsByNameAscSurnameDesc = _.sort(persons, [
    _.getKey("name"),
    _.sorterDesc(_.getKey("surname"))
]);

// personsByNameAscSurnameDesc holds:
// [
//     {"name": "Jane", "surname": "Foe"},
//     {"name": "John", "surname" :"Moe"},
//     {"name": "John", "surname" :"Doe"},
//     {"name": "Mario", "surname": "Rossi"}
// ]

Using custom comparers:

const localeSorter = new Intl.Collator("it");
const chars = ["a", "è", "à", "é", "c", "b", "e"];

_.sort(chars, [localeSorter]) // => ["a", "à", "b", "c", "e", "é", "è"]

const localeSorterDesc = _.sorterDesc(_.identity, localeSorter.compare);

_.sort(chars, [localeSorterDesc]) // => ["è", "é", "e", "c", "b", "à", "a"]

sortedInsert(arrayLike, element, sortersopt) → {Array} Array

Inserts an element in a copy of a sorted array respecting the sort order.
Parameters:
Name Type Attributes Default Description
arrayLike ArrayLike
element *
sorters Array.<Sorter> | Array.<function()> <optional>
[sorter()] The sorting criteria used to sort the array.
Since:
  • 0.27.0
Source:
See:
Returns:

Type Array

Examples

With simple values:

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

With complex values:

const persons = [
    {"name": "jane", "surname": "doe"},
    {"name": "John", "surname": "Doe"},
    {"name": "Mario", "surname": "Rossi"}
];

const getLowerCaseName = _.compose(
    _.invoke("toLowerCase"),
    _.getKey("name")
);

const result = _.sortedInsert(
    persons,
    {"name": "marco", "surname": "Rossi"},
    getLowerCaseName
);

// `result` holds:
// [
//     {"name": "jane", "surname": "doe"},
//     {"name": "John", "surname": "Doe"},
//     {"name": "marco", "surname": "Rossi"},
//     {"name": "Mario", "surname": "Rossi"}
// ]

sorter(readeropt, compareropt) → {Sorter} Array

Creates an ascending sort criterion with the provided reader and comparer.
See sort for various examples.
Parameters:
Name Type Attributes Default Description
reader function <optional>
identity A function meant to generate a simple value from a complex one. The function should evaluate the array element and supply the value to be passed to the comparer.
comparer function <optional>
An optional custom comparer function.
Since:
  • 0.1.0
Source:
See:
Returns:

Type Sorter

sorterDesc(readeropt, compareropt) → {Sorter} Array

Creates a descending sort criterion with the provided reader and comparer.
See sort for various examples.
Parameters:
Name Type Attributes Default Description
reader function <optional>
identity A function meant to generate a simple value from a complex one. The function should evaluate the array element and supply the value to be passed to the comparer.
comparer function <optional>
An optional custom comparer function.
Since:
  • 0.15.0
Source:
See:
Returns:

Type Sorter

sortWith(sortersopt) → {function} Array

Builds a partial application of sort using the provided criteria. The returned function expects the array-like object to sort. As usual, sorting criteria are built using Lamb's sorter function, but you can also pass simple "reader" functions and default ascending sorters will be built.
A "reader" is a function that evaluates the array element and supplies the value to be used in the comparison.
See sort for more examples.
Parameters:
Name Type Attributes Default Description
sorters Array.<Sorter> | Array.<function()> <optional>
[sorter()]
Since:
  • 0.15.0
Source:
See:
Returns:

Type function

Example
var sortAsNumbers = _.sortWith([parseFloat]);
var weights = ["2 Kg", "10 Kg", "1 Kg", "7 Kg"];

sortAsNumbers(weights) // => ["1 Kg", "2 Kg", "7 Kg", "10 Kg"]

split(source, separator) → {Array.<String>} String

Splits a string into an array of substrings using the given separator.
Parameters:
Name Type Description
source String
separator String | RegExp
Since:
  • 0.59.0
Source:
See:
Returns:

Type Array.<String>

Example
_.split("Jan,Feb,Mar,Apr,May", ",") // => ["Jan", "Feb", "Mar", "Apr", "May"]
_.split("Jan, Feb , Mar,Apr,   May", /\s*,\s*‍/) // => ["Jan", "Feb", "Mar", "Apr", "May"]

splitBy(separator) → {function} String

A curried version of split that accepts a separator and builds a function expecting the string to split.
Parameters:
Name Type Description
separator String | RegExp
Since:
  • 0.59.0
Source:
See:
Returns:

Type function

Example
const splitByCommma = _.splitBy(",");

splitByCommma("Jan,Feb,Mar,Apr,May") // => ["Jan", "Feb", "Mar", "Apr", "May"]

subtract(a, b) → {Number} Math

Subtracts two numbers.
Parameters:
Name Type Description
a Number
b Number
Since:
  • 0.1.0
Source:
See:
Returns:

Type Number

Example
_.subtract(5, 3) // => 2

sum(a, b) → {Number} Math

Sums two numbers.
Parameters:
Name Type Description
a Number
b Number
Since:
  • 0.50.0
Source:
See:
Returns:

Type Number

Example
_.sum(4, 5) // => 9

tail(arrayLike) → {Array} Array

Returns a copy of the given array-like object without the first element.
Parameters:
Name Type Description
arrayLike ArrayLike
Since:
  • 0.16.0
Source:
See:
Returns:

Type Array

Example
_.tail([1, 2, 3, 4]) // => [2, 3, 4]
_.tail([1]) // => []
_.tail([]) // => []

take(n) → {function} Array

A curried version of takeFrom that expects the number of elements to retrieve to build a function waiting for the list to take the elements from.
See the note and examples for takeFrom about passing a negative n.
Parameters:
Name Type Description
n Number
Since:
  • 0.5.0
Source:
See:
Returns:

Type function

Example
const take2 = _.take(2);

take2([1, 2, 3, 4, 5]) // => [1, 2]

takeFrom(arrayLike, n) → {Array} Array

Retrieves the first n elements from an array or array-like object.
Note that, being this a shortcut for a common use case of slice, n can be a negative number.
Parameters:
Name Type Description
arrayLike ArrayLike
n Number
Since:
  • 0.51.0
Source:
See:
Returns:

Type Array

Example
const arr = [1, 2, 3, 4, 5];

_.takeFrom(arr, 3) // => [1, 2, 3]
_.takeFrom(arr, -1) // => [1, 2, 3, 4]
_.takeFrom(arr, -10) // => []

takeLastWhile(predicate) → {function} Array

Builds a function that takes the last elements satisfying a predicate from an array or array-like object.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.58.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const takeLastWhileIsEven = _.takeLastWhile(isEven);

takeLastWhileIsEven([1, 3, 5, 7]) // => []
takeLastWhileIsEven([2, 3, 6, 8]) // => [6, 8]

takeWhile(predicate) → {function} Array

Builds a function that takes the first elements satisfying a predicate from an array or array-like object.
Parameters:
Name Type Description
predicate ListIteratorCallback
Since:
  • 0.5.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const takeWhileIsEven = _.takeWhile(isEven);

takeWhileIsEven([1, 2, 4, 6, 8]) // => []
takeWhileIsEven([2, 4, 7, 8]) // => [2, 4]

tapArgs(fn, tappers) → {function} Function

Builds a function that allows to "tap" into the arguments of the original one. This allows to extract simple values from complex ones, transform arguments or simply intercept them. If a "tapper" isn't found the argument is passed as it is.
Parameters:
Name Type Description
fn function
tappers Array.<function()>
Since:
  • 0.3.0
Source:
See:
Returns:

Type function

Example
const someObject = {count: 5};
const someArrayData = [2, 3, 123, 5, 6, 7, 54, 65, 76, 0];
const getDataAmount = _.tapArgs(_.sum, [_.getKey("count"), _.getKey("length")]);

getDataAmount(someObject, someArrayData); // => 15

tear(obj) → {Array.<Array.<String>, Array>} Object

Tears an object apart by transforming it in an array of two lists: one containing its enumerable keys, the other containing the corresponding values.
Although this "tearing apart" may sound as a rather violent process, the source object will be unharmed.
Parameters:
Name Type Description
obj Object
Since:
  • 0.8.0
Source:
See:
Returns:

Type Array.<Array.<String>, Array>

Example
_.tear({a: 1, b: 2, c: 3}) // => [["a", "b", "c"], [1, 2, 3]]

tearOwn(obj) → {Array.<Array.<String>, Array>} Object

Same as tear, but only the own properties of the object are taken into account.
Parameters:
Name Type Description
obj Object
Since:
  • 0.12.0
Source:
See:
Returns:

Type Array.<Array.<String>, Array>

Example

Showing the difference with tear:

const baseFoo = Object.create({a: 1}, {b: {value: 2, enumerable: true}, z: {value: 5}});
const foo = Object.create(baseFoo, {
    c: {value: 3, enumerable: true}
});

_.tear(foo) // => [["c", "b", "a"], [3, 2, 1]]
_.tearOwn(foo) // => [["c"], [3]]

testWith(pattern) → {function} String

Builds a predicate expecting a string to test against the given regular expression pattern.
Parameters:
Name Type Description
pattern RegExp
Since:
  • 0.1.0
Source:
Returns:

Type function

Example
const hasNumbersOnly = _.testWith(/^\d+$/);

hasNumbersOnly("123") // => true
hasNumbersOnly("123 Kg") // => false

throttle(fn, timespan) → {function} Function

Returns a function that will invoke the passed function at most once in the given timespan.
The first call in this case happens as soon as the function is invoked; see also debounce for a different behaviour where the first call is delayed.
Parameters:
Name Type Description
fn function
timespan Number Expressed in milliseconds.
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const log = _.throttle(console.log.bind(console), 5000);

log("Hi"); // console logs "Hi"
log("Hi again"); // nothing happens
// after five seconds
log("Hello world"); // console logs "Hello world"

transpose(arrayLike) → {Array.<Array>} Array

Transposes a matrix. Can also be used to reverse a zip operation.
Just like zip, the received array-like objects will be truncated to the shortest length.
Parameters:
Name Type Description
arrayLike ArrayLike.<ArrayLike>
Since:
  • 0.14.0
Source:
See:
Returns:

Type Array.<Array>

Examples

Transposing a matrix:

_.transpose([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]) // =>
// [
//     [1, 4, 7],
//     [2, 5, 8],
//     [3, 6, 9]
// ]

Showing the relationship with zip:

const zipped = _.zip(["a", "b", "c"], [1, 2, 3]); // => [["a", 1], ["b", 2], ["c", 3]]

_.transpose(zipped) // => [["a", "b", "c"], [1, 2, 3]]

type(value) → {String} Type

Retrieves the "type tag" from the given value.
Parameters:
Name Type Description
value *
Since:
  • 0.9.0
Source:
See:
Returns:

Type String

Example
const x = 5;
const y = new Number(5);

typeof x // => "number"
typeof y // => "object"
_.type(x) // => "Number"
_.type(y) // => "Number"

_.type(Object.prototype.toString) // => "Function"
_.type(/a/) // => "RegExp"

unary(fn) → {function} Function

Builds a function that passes only one argument to the given function.
It's simply a shortcut for a common use case of aritize, exposed for convenience.
Parameters:
Name Type Description
fn function
Since:
  • 0.10.0
Source:
See:
Returns:

Type function

Example
const weights = ["2 Kg", "10 Kg", "1 Kg", "7 Kg"];

_.map(weights, _.unary(parseInt)) // => [2, 10, 1, 7]

union(a, b) → {Array} Array

Returns a list of every unique element present in the two given array-like objects.
Uses the "SameValueZero" comparison to test the equality of values.
When two values are considered equal, the first occurence will be the one included in the result array.
See also unionBy if you need to transform the values before the comparison or if you have to extract them from complex ones.
Parameters:
Name Type Description
a ArrayLike
b ArrayLike
Since:
  • 0.5.0
Source:
See:
Returns:

Type Array

Example
_.union([1, 2, 3, 2], [2, 3, 4]) // => [1, 2, 3, 4]
_.union("abc", "bcd") // => ["a", "b", "c", "d"]

unionBy(iteratee) → {function} Array

Using the provided iteratee to transform values, builds a function that will return an array of the unique elements in the two provided array-like objects.
Uses the "SameValueZero" comparison to test the equality of values.
When two values are considered equal, the first occurence will be the one included in the result array.
See also union if you don't need to compare transformed values.
Parameters:
Name Type Description
iteratee ListIteratorCallback
Since:
  • 0.51.0
Source:
See:
Returns:

Type function

Example
const unionByFloor = _.unionBy(Math.floor);

unionByFloor([2.8, 3.2, 1.5], [3.5, 1.2, 4]) // => [2.8, 3.2, 1.5, 4]

uniques(arrayLike) → {Array} Array

Returns an array comprised of the unique elements of the given array-like object.
Note that this function uses the "SameValueZero" comparison to test the equality of values.
When two values are considered equal, the first occurence will be the one included in the result array.
See also uniquesBy if you need to transform your values before the comparison or if you have to extract them from complex ones.
Parameters:
Name Type Description
arrayLike ArrayLike
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example
_.uniques([-0, 1, 2, 0, 2, 3, 4, 3, 5, 1]) // => [-0, 1, 2, 3, 4, 5]

uniquesBy(iteratee) → {function} Array

Using the provided iteratee, builds a function that will return an array comprised of the unique elements of an array-like object. The values being compared are the ones returned by the iteratee.
The equality test is made with the "SameValueZero" comparison.
When two values are considered equal, the first occurence will be the one included in the result array.
See also uniques if you don't need to transform your values before the comparison.
Parameters:
Name Type Description
iteratee ListIteratorCallback
Since:
  • 0.51.0
Source:
See:
Returns:

Type function

Example
const data  = [
    {id: "1", name: "John"},
    {id: "4", name: "Jane"},
    {id: "5", name: "Joe"},
    {id: "1", name: "Mario"},
    {id: "5", name: "Paolo"},
];
const uniquesById = _.uniquesBy(_.getKey("id"));

uniquesById(data) // => [{id: "1", name: "John"}, {id: "4", name: "Jane"}, {id: "5", name: "Joe"}]

unless(predicate, fn) → {function} Logic

Builds a unary function that will check its argument against the given predicate. If the predicate isn't satisfied, the provided fn function will be applied to the same value. The received argument is returned as it is otherwise.
See when for the opposite behaviour.
It's a shortcut for a common use case of condition, where its trueFn parameter is the identity function.
Parameters:
Name Type Description
predicate function
fn function
Since:
  • 0.42.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const halveUnlessIsEven = _.unless(isEven, _.divideBy(2));

halveUnlessIsEven(5) // => 2.5
halveUnlessIsEven(6) // => 6

updateAt(index, updater) → {function} Array

Builds a function that creates a copy of an array-like object with the given index changed by applying the provided function to its value.
If the index is not an integer or if it's out of bounds, the function will return a copy of the original array.
Negative indexes are allowed.
Parameters:
Name Type Description
index Number
updater function
Since:
  • 0.22.0
Source:
See:
Returns:

Type function

Example
const arr = ["a", "b", "c"];
const toUpperCase = _.invoke("toUpperCase");

_.updateAt(1, toUpperCase)(arr) // => ["a", "B", "c"]
_.updateAt(-1, toUpperCase)(arr) // => ["a", "b", "C"]
_.updateAt(10, toUpperCase)(arr) // => ["a", "b", "c"] (not a reference to `arr`)

updateIn(source, key, updater) → {Object} Object

Creates a copy of the given object having the desired key value updated by applying the provided function to it.
This function is meant for updating existing enumerable properties, and for those it will delegate the "set action" to setIn; a copy of the source is returned otherwise.
Parameters:
Name Type Description
source Object
key String
updater function
Since:
  • 0.22.0
Source:
See:
Returns:

Type Object

Examples
const user = {name: "John", visits: 2};
const toUpperCase = _.invoke("toUpperCase");

_.updateIn(user, "name", toUpperCase) // => {name: "JOHN", visits: 2}
_.updateIn(user, "surname", toUpperCase) // => {name: "John", visits: 2}

Non-enumerable properties will be treated as non-existent:

const user = Object.create({name: "John"}, {visits: {value: 2}});

_.updateIn(user, "visits", _.add(1)) // => {name: "John", visits: 2}

updateIndex(arrayLike, index, updater) → {Array} Array

Creates a copy of an array-like object with the given index changed by applying the provided function to its value.
If the index is not an integer or if it's out of bounds, the function will return a copy of the original array.
Negative indexes are allowed.
Parameters:
Name Type Description
arrayLike ArrayLike
index Number
updater function
Since:
  • 0.23.0
Source:
See:
Returns:

Type Array

Example
const arr = ["a", "b", "c"];
const toUpperCase = _.invoke("toUpperCase");

_.updateIndex(arr, 1, toUpperCase) // => ["a", "B", "c"]
_.updateIndex(arr, -1, toUpperCase) // => ["a", "b", "C"]
_.updateIndex(arr, 10, toUpperCase) // => ["a", "b", "c"] (not a reference to `arr`)

updateKey(key, updater) → {function} Object

Builds a partial application of updateIn with the provided key and updater, expecting the object to act upon.
This function is meant for updating existing enumerable properties, and for those it will delegate the "set action" to setIn; a copy of the source is returned otherwise.
Parameters:
Name Type Description
key String
updater function
Since:
  • 0.22.0
Source:
See:
Returns:

Type function

Example
const user = {name: "John", visits: 2};
const incrementVisits = _.updateKey("visits", _.add(1));

incrementVisits(user) // => {name: "John", visits: 3}

updatePath(path, updater, separatoropt) → {function} Object

Builds a partial application of updatePathIn expecting the object to act upon.
This function is meant for updating existing enumerable properties, and for those it will delegate the "set action" to setPathIn; a copy of the source is returned otherwise.
Like the other "path" functions, negative indexes can be used to access array elements, but the priority will be given to existing, and enumerable, object keys.
Parameters:
Name Type Attributes Default Description
path String
updater function
separator String <optional>
"."
Since:
  • 0.24.0
Source:
See:
Returns:

Type function

Example
const user = {id: 1, status: {scores: [2, 4, 6], visits: 0}};
const incrementScores = _.updatePath("status.scores", _.mapWith(_.add(1)))

incrementScores(user) // => {id: 1, status: {scores: [3, 5, 7], visits: 0}}

updatePathIn(source, path, updater, separatoropt) → {Object|Array} Object

Allows to change a nested value in a copy of the given object by applying the provided function to it.
This function is meant for updating existing enumerable properties, and for those it will delegate the "set action" to setPathIn; a copy of the source is returned otherwise.
Like the other "path" functions, negative indexes can be used to access array elements, but the priority will be given to existing, and enumerable, object keys.
Parameters:
Name Type Attributes Default Description
source Object | Array
path String
updater function
separator String <optional>
"."
Since:
  • 0.24.0
Source:
See:
Returns:

Type Object | Array

Examples
const user = {id: 1, status: {scores: [2, 4, 6], visits: 0}};
const inc = _.add(1);

_.updatePathIn(user, "status.visits", inc) // => {id: 1, status: {scores: [2, 4, 6]}, visits: 1}

Targeting arrays:

_.updatePathIn(user, "status.scores.0", inc) // => {id: 1, status: {scores: [3, 4, 6], visits: 0}}

// you can use negative indexes as well
_.updatePathIn(user, "status.scores.-1", inc) // => {id: 1, status: {scores: [2, 4, 7], visits: 0}}

Arrays can also be part of the path and not necessarily its target:

const user = {
    id: 1,
    scores: [
        {value: 2, year: "2000"},
        {value: 4, year: "2001"},
        {value: 6, year: "2002"}
    ]
};

const newUser = _.updatePathIn(user, "scores.0.value", inc);
// "newUser" holds:
// {
//     id: 1,
//     scores: [
//         {value: 3, year: "2000"},
//         {value: 4, year: "2001"},
//         {value: 6, year: "2002"}
//     ]
// }

validate(obj, checkers) → {Array.<Array.<String, Array.<String>>>} Object

Validates an object with the given list of checker functions.
Parameters:
Name Type Description
obj Object
checkers Array.<function()>
Since:
  • 0.1.0
Source:
See:
Returns:
An array of errors in the form returned by checker, or an empty array.

Type Array.<Array.<String, Array.<String>>>

Example
const hasContent = s => s.trim().length > 0;
const userCheckers = [
    _.checker(hasContent, "Name is required", ["name"]),
    _.checker(hasContent, "Surname is required", ["surname"]),
    _.checker(_.isGTE(18), "Must be at least 18 years old", ["age"])
];

const user1 = {name: "john", surname: "doe", age: 30};
const user2 = {name: "jane", surname: "", age: 15};

_.validate(user1, userCheckers) // => []
_.validate(user2, userCheckers) // =>
// [
//     ["Surname is required", ["surname"]],
//     ["Must be at least 18 years old", ["age"]]
// ]

validateWith(checkers) → {function} Object

A curried version of validate accepting a list of checkers and returning a function expecting the object to validate.
Parameters:
Name Type Description
checkers Array.<function()>
Since:
  • 0.1.0
Source:
See:
Returns:

Type function

Example
const hasContent = s => s.trim().length > 0;
const userCheckers = [
    _.checker(hasContent, "Name is required", ["name"]),
    _.checker(hasContent, "Surname is required", ["surname"]),
    _.checker(_.isGTE(18), "Must be at least 18 years old", ["age"])
];
const validateUser = _.validateWith(userCheckers);

const user1 = {name: "john", surname: "doe", age: 30};
const user2 = {name: "jane", surname: "", age: 15};

validateUser(user1) // => []
validateUser(user2) // =>
// [
//     ["Surname is required", ["surname"]],
//     ["Must be at least 18 years old", ["age"]]
// ]

values(obj) → {Array} Object

Generates an array with the values of the enumerable properties of the given object.
See also ownValues to pick only from the own properties of the object.
Parameters:
Name Type Description
obj Object
Since:
  • 0.1.0
Source:
See:
Returns:

Type Array

Example
const user = {name: "john", surname: "doe", age: 30};

_.values(user) // => ["john", "doe", 30]

when(predicate, fn) → {function} Logic

Builds a unary function that will check its argument against the given predicate. If the predicate is satisfied, the provided fn function will be applied to the same value. The received argument is returned as it is otherwise.
See unless for the opposite behaviour.
It's a shortcut for a common use case of condition, where its falseFn parameter is the identity function.
Parameters:
Name Type Description
predicate function
fn function
Since:
  • 0.42.0
Source:
See:
Returns:

Type function

Example
const isEven = n => n % 2 === 0;
const halveIfEven = _.when(isEven, _.divideBy(2));

halveIfEven(5) // => 5
halveIfEven(6) // => 3

zip(a, b) → {Array.<Array>} Array

Builds a list of arrays out of the two given array-like objects by pairing items with the same index.
The received array-like objects will be truncated to the shortest length.
Parameters:
Name Type Description
a ArrayLike
b ArrayLike
Since:
  • 0.14.0
Source:
See:
Returns:

Type Array.<Array>

Example
_.zip(
    ["a", "b", "c"],
    [1, 2, 3]
) // => [["a", 1], ["b", 2], ["c", 3]]

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

zipWithIndex(arrayLike) → {Array.<Array.<*, Number>>} Array

"Zips" an array-like object by pairing its values with their index.
Parameters:
Name Type Description
arrayLike ArrayLike
Since:
  • 0.14.0
Source:
See:
Returns:

Type Array.<Array.<*, Number>>

Example
_.zipWithIndex(["a", "b", "c"]) // => [["a", 0], ["b", 1], ["c", 2]]