Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers. However, when you are targeting modern browsers, you may find out that there are many methods which are already supported natively thanks to ECMAScript5 [ES5] and ECMAScript2015 [ES6]. If you want your project to require fewer dependencies, and you know your target browser clearly, then you may not need Lodash/Underscore.
You are welcome to contribute with more items provided below.
-
If you are targeting legacy JavaScript engine with those ES5 methods, you can use es5-shim
-
Please note that, the examples used below are just showing you the native alternative of performing certain tasks. For some functions, Lodash provides you more options than native built-ins. This list is not a 1:1 comparison.
-
Please send a PR if you want to add or modify the code. No need to open an issue unless it's something big and you want to discuss.
Voice of Developers
Make use of native JavaScript object and array utilities before going big.
—Cody Lindley, Author of jQuery Cookbook and JavaScript Enlightenment
You probably don't need Lodash. Nice List of JavaScript methods which you can use natively.
—Daniel Lamb, Computer Scientist, Technical Reviewer of Secrets of the JavaScript Ninja and Functional Programming in JavaScript
I guess not, but I want it.
—Tero Parviainen, Author of build-your-own-angular
I'll admit, I've been guilty of overusing #lodash. Excellent resource.
—@therebelrobot, Maker of web things, Facilitator for Node.js/io.js
ESLint Plugin
If you're using ESLint, you can install a
plugin that
will help you identify places in your codebase where you don't (may not) need Lodash/Underscore.
Install the plugin ...
npm install --save-dev eslint-plugin-you-dont-need-lodash-underscore
... then update your config
"extends" : ["plugin:you-dont-need-lodash-underscore/compatible"],
For more information, see Configuring the ESLint Plugin
[!IMPORTANT]
Note that, while many Lodash methods are null safe (e.g. _.keys, _.entries),
this is not necessarily the case for their Native equivalent. If null safety is critical for your application, we
suggest that you take extra precautions [e.g. consider using the native Object.keys
as Object.keys(value || {})
].
Quick Links
Array
- _.chunk
- _.compact
- _.concat
- _.difference
- _.drop
- _.dropRight
- _.fill
- _.find
- _.findIndex
- _.first
- _.flatten
- _.flattenDeep
- _.fromPairs
- _.head and _.tail
- _.indexOf
- _.intersection
- _.isArray
- _.isArrayBuffer
- _.join
- _.last
- _.lastIndexOf
- _.reverse
- _.slice
- _.without
- _.initial
- _.pull
- _.unionBy
Collection*
[!IMPORTANT]
Note that most native equivalents are array methods,
and will not work with objects. If this functionality is needed and no object method is provided,
then Lodash/Underscore might be the better option. Bear in mind however, that all iterable
objects can easily be converted to an array by use of the
spread operator.
- _.each
- _.every
- _.filter
- _.groupBy
- _.includes
- _.keyBy
- _.map
- _.minBy and _.maxBy
- _.orderBy
- _.pluck
- _.range
- _.reduce
- _.reduceRight
- _.reject
- _.size
- _.some
- _.sortBy
- _.uniq
- _.uniqWith
Function
- _.after
- _.bind
- _.debounce
- _.isFunction
- _.partial
- _.throttle
Lang
- _.castArray
- .cloneDeep
- _.gt
- _.gte
- _.isDate
- _.isEmpty
- _.isFinite
- _.isInteger
- _.isNaN
- _.isNil
- _.isNull
- _.isUndefined
Object
- _.assign
- _.defaults
- _.extend
- _.has
- _.get
- _.invert
- _.isPlainObject
- _.keys
- _.mapKeys
- _.omit
- _.pick
- _.pickBy
- _.toPairs
- _.values
String
- _.capitalize
- _.endsWith
- _.isString
- _.lowerFirst
- _.padStart and _.padEnd
- _.repeat
- _.replace
- _.split
- _.startsWith
- _.template
- _.toLower
- _.toUpper
- _.trim
- _.upperFirst
Util
- _.times
Number
- _.clamp
- _.inRange
- _.random
Array
_.chunk
Creates an array of elements split into groups the length of size.
_.chunk(['a', 'b', 'c', 'd'], 2);
_.chunk(['a', 'b', 'c', 'd'], 3);
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
return idx % size === 0
? [...arr, [item]]
: [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
}, []);
};
chunk(['a', 'b', 'c', 'd'], 2);
chunk(['a', 'b', 'c', 'd'], 3);
Browser Support for Spread in array literals
| | | | | |
---|
46.0 ✔ | 12.0 ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 8.0 ✔ |
⬆ back to top
_.compact
Creates an array with all falsy values removed.
_.compact([0, 1, false, 2, '', 3]);
[0, 1, false, 2, '', 3].filter(Boolean)
Browser Support for array.prototype.filter
⬆ back to top
_.concat
Creates a new array concatenating array with any additional arrays and/or values.
var array = [1]
var other = _.concat(array, 2, [3], [[4]])
console.log(other)
var array = [1]
var other = array.concat(2, [3], [[4]])
console.log(other)
Browser Support for Array.prototype.concat()
⬆ back to top
_.difference
Similar to without, but returns the values from array that are not present in the other arrays.
console.log(_.difference([1, 2, 3, 4, 5], [5, 2, 10]))
var arrays = [[1, 2, 3, 4, 5], [5, 2, 10]];
console.log(arrays.reduce(function(a, b) {
return a.filter(function(value) {
return !b.includes(value);
});
}));
let arrays = [[1, 2, 3, 4, 5], [5, 2, 10]];
console.log(arrays.reduce((a, b) => a.filter(c => !b.includes(c))));
Browser Support for Array.prototype.reduce()
⬆ back to top
_.drop
Creates a slice of array with n elements dropped from the beginning.
_.drop([1, 2, 3]);
_.drop([1, 2, 3], 2);
[1, 2, 3].slice(1);
[1, 2, 3].slice(2);
Browser Support for Array.prototype.slice()
⬆ back to top
_.dropRight
Creates a slice of array with n elements dropped at the end.
_.dropRight([1, 2, 3]);
_.dropRight([1, 2, 3], 2);
[1, 2, 3].slice(0, -1);
[1, 2, 3].slice(0, -2);
Browser Support for Array.prototype.slice()
⬆ back to top
_.fill
Fills elements of array with value from start up to, but not including, end.
[!NOTE]
fill
is a mutable method in both native and Lodash/Underscore.
var array = [1, 2, 3]
_.fill(array, 'a')
console.log(array)
_.fill(Array(3), 2)
_.fill([4, 6, 8, 10], '*', 1, 3)
var array = [1, 2, 3]
array.fill('a')
console.log(array)
Array(3).fill(2)
[4, 6, 8, 10].fill('*', 1, 3)
Browser Support for Array.prototype.fill()
⬆ back to top
_.find
Returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
]
_.find(users, function (o) { return o.age < 40; })
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
]
users.find(function (o) { return o.age < 40; })
Browser Support for Array.prototype.find()
| | | | | |
---|
45.0 ✔ | ✔ | 25.0 ✔ | ✖ | 32.0 ✔ | 7.1 ✔ |
⬆ back to top
_.findIndex
Returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
]
var index = _.findIndex(users, function (o) { return o.age >= 40; })
console.log(index)
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
]
var index = users.findIndex(function (o) { return o.age >= 40; })
console.log(index)
Browser Support for Array.prototype.findIndex()
| | | | | |
---|
45.0 ✔ | ✔ | 25.0 ✔ | ✖ | 32.0 ✔ | 7.1 ✔ |
⬆ back to top
_.first
Returns the first element of an array. Passing n will return the first n elements of the array.
_.first([1, 2, 3, 4, 5]);
_.first([1, 2, 3, 4, 5], 2);
[1, 2, 3, 4, 5][0];
[].concat(1, 2, 3, 4, 5).shift()
[].concat([1, 2, 3, 4, 5]).shift()
[].concat(undefined).shift()
[1, 2, 3, 4, 5].slice(0, 2);
[1, 2, 3, 4, 5].at(0)
[].at(0)
Browser Support for Array.prototype.slice()
Browser Support for Array.prototype.at()
⬆ back to top
_.flatten
Flattens array a single level deep.
_.flatten([1, [2, [3, [4]], 5]]);
const flatten = [1, [2, [3, [4]], 5]].reduce( (a, b) => a.concat(b), [])
const flatten = [].concat(...[1, [2, [3, [4]], 5]])
const flatten = [1, [2, [3, [4]], 5]].flat()
const flatten = [1, [2, [3, [4]], 5]].flatMap(number => number)
Browser Support for Array.prototype.reduce()
| | | | | |
---|
46.0 ✔ | ✔ | 3.0 ✔ | 9.0 ✔ | 10.5 ✔ | 4 ✔ |
Browser Support for Array.prototype.flat()
Browser Support for Array.prototype.flatMap()
⬆ back to top
_.flattenDeep
Recursively flattens array.
_.flattenDeep([1, [2, [3, [4]], 5]]);
const flattenDeep = (arr) => Array.isArray(arr)
? arr.reduce( (a, b) => a.concat(flattenDeep(b)) , [])
: [arr]
flattenDeep([1, [[2], [3, [4]], 5]])
[1, [2, [3, [4]], 5]].flat(Infinity)
const flattenDeep = (arr) => arr.flatMap((subArray, index) => Array.isArray(subArray) ? flattenDeep(subArray) : subArray)
flattenDeep([1, [[2], [3, [4]], 5]])
Browser Support
| | | | | |
---|
46.0 ✔ | ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 7.1 ✔ |
Browser Support for Array.prototype.flat()
Browser Support for Array.prototype.flatMap()
⬆ back to top
_.fromPairs
Returns an object composed from key-value pairs.
_.fromPairs([['a', 1], ['b', 2]]);
const fromPairs = function(arr) {
return arr.reduce(function(accumulator, value) {
accumulator[value[0]] = value[1];
return accumulator;
}, {})
}
const fromPairs = (arr) => arr.reduce((acc, val) => (acc[val[0]] = val[1], acc), {})
fromPairs([['a', 1], ['b', 2]]);
Object.fromEntries([['a', 1], ['b', 2]])
Browser Support for Array.prototype.reduce()
Browser Support for Object.fromEntries()
| | | | | |
---|
73.0 ✔ | 79.0 ✔ | 63.0 ✔ | ✖ | 60 ✔ | 12.1 ✔ |
⬆ back to top
_.head and _.tail
Gets the first element or all but the first element.
const array = [1, 2, 3]
_.head(array)
_.tail(array)
const [ head, ...tail ] = array
console.log(head)
console.log(tail)
array.at(0)
Browser Support for Spread in array literals
| | | | | |
---|
46.0 ✔ | 12.0 ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 8.0 ✔ |
Browser Support for Array.prototype.at()
⬆ back to top
_.indexOf
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
var array = [2, 9, 9]
var result = _.indexOf(array, 2)
console.log(result)
var array = [2, 9, 9]
var result = array.indexOf(2)
console.log(result)
Browser Support for Array.prototype.indexOf()
⬆ back to top
_.intersection
Returns an array that is the intersection of all the arrays. Each value in the result is present in each of the arrays.
console.log(_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]))
var arrays = [[1, 2, 3], [101, 2, 1, 10], [2, 1]];
console.log(arrays.reduce(function(a, b) {
return a.filter(function(value) {
return b.includes(value);
});
}));
let arrays = [[1, 2, 3], [101, 2, 1, 10], [2, 1]];
console.log(arrays.reduce((a, b) => a.filter(c => b.includes(c))));
Browser Support for Array.prototype.reduce()
⬆ back to top
_.takeRight
Creates a slice of array with n elements taken from the end.
[!IMPORTANT]
Native slice does not behave entirely the same as the Lodash
method. See example below to understand why.
_.takeRight([1, 2, 3]);
_.takeRight([1, 2, 3], 2);
_.takeRight([1, 2, 3], 5);
[1, 2, 3].slice(-1);
[1, 2, 3].slice(-2);
[1, 2, 3].slice(-5);
_.takeRight([1, 2, 3], 0);
[1, 2, 3].slice(0);
Browser Support for Array.prototype.slice()
⬆ back to top
_.isArray
Returns true if given value is an array.
var array = []
console.log(_.isArray(array))
var array = []
console.log(Array.isArray(array));
Browser Support for Array.isArray()
| | | | | |
---|
5.0 ✔ | ✔ | 4.0 ✔ | 9.0 ✔ | 10.5 ✔ | 5.0 ✔ |
⬆ back to top
_.isArrayBuffer
Checks if value is classified as an ArrayBuffer object.
_.isArrayBuffer(new ArrayBuffer(2));
console.log(new ArrayBuffer(2) instanceof ArrayBuffer);
[!WARNING]
You will get the wrong result if you get ArrayBuffer
from another realm.
See details.
Browser Support for instanceof
⬆ back to top
_.join
[!IMPORTANT]
Not in Underscore.js
Joins a list of elements in an array with a given separator.
var result = _.join(['one', 'two', 'three'], '--')
console.log(result)
var result = ['one', 'two', 'three'].join('--')
console.log(result)
Browser Support for Array.prototype.join()
⬆ back to top
_.last
Returns the last element of an array. Passing n will return the last n elements of the array.
const numbers = [1, 2, 3, 4, 5];
_.last(numbers);
_.last(numbers, 2);
const numbers = [1, 2, 3, 4, 5];
numbers[numbers.length - 1];
numbers.slice(-1)[0];
[].concat(numbers).pop()
numbers.at(-1);
[].concat(undefined).pop()
numbers.slice(-2);
Browser Support for Array.prototype.concat()
Browser Support for Array.prototype.at()
⬆ back to top
_.lastIndexOf
Returns the index of the last occurrence of value in the array, or -1 if value is not present.
var array = [2, 9, 9, 4, 3, 6]
var result = _.lastIndexOf(array, 9)
console.log(result)
var array = [2, 9, 9, 4, 3, 6]
var result = array.lastIndexOf(9)
console.log(result)
Browser Support for Array.prototype.lastIndexOf()
⬆ back to top
_.reverse
[!IMPORTANT]
Not in Underscore.js
Reverses array so that the first element becomes the last, the second element becomes the second to last, and so on.
var array = [1, 2, 3]
console.log(_.reverse(array))
var array = [1, 2, 3]
console.log(array.reverse())
Voice from the Lodash author:
Lodash's _.reverse
just calls Array#reverse
and enables composition like _.map(arrays, _.reverse).
It's exposed on _ because previously, like Underscore
, it was only exposed in the chaining syntax.
--- jdalton
Browser Support for Array.prototype.reverse()
⬆ back to top
_.slice
Returns a shallow copy of a portion of an array into a new array object selected from begin
to end
(end
not included)
var array = [1, 2, 3, 4]
console.log(_.slice(array, 1, 3))
var array = [1, 2, 3, 4]
console.log(array.slice(1, 3));
Browser Support for Array.prototype.slice()
⬆ back to top
_.without
[!IMPORTANT]
Not in Underscore.js
Returns an array where matching items are filtered.
var array = [1, 2, 3]
console.log(_.without(array, 2))
var array = [1, 2, 3]
console.log(array.filter(function(value) {
return value !== 2;
}));
Browser Support for Array.prototype.filter()
⬆ back to top
_.initial
Returns everything but the last entry of the array. Pass n to exclude the last n elements from the result.
var array = [5, 4, 3, 2, 1]
console.log(_.initial(array, 2))
var array = [5, 4, 3, 2, 1]
console.log(array.slice(0, -2));
Browser Support for Array.prototype.slice()
⬆ back to top
_.pull
Removes all provided values from the given array using strict equality for comparisons, i.e. ===.
const array = [1, 2, 3, 1, 2, 3];
_.pull(array, 2, 3);
console.log(array);
const array = [1, 2, 3, 1, 2, 3];
function pull(arr, ...removeList){
var removeSet = new Set(removeList)
return arr.filter(function(el){
return !removeSet.has(el)
})
}
console.log(pull(array, 2, 3));
console.log(array);
const array = [1, 2, 3, 1, 2, 3];
const pull = <T extends unknown>(sourceArray: T[], ...removeList: T[]): T[] => {
const removeSet = new Set(removeList);
return sourceArray.filter(el => !removeSet.has(el));
};
console.log(pull(array, 2, 3));
console.log(array);
Browser Support for Array.prototype.filter()
Browser Support for Set.prototype.has()
⬆ back to top
_.unionBy
Creates an array of unique values, taking an iteratee
to compute uniqueness with
(note that to iterate by a key in an object you must use x => x.key
instead of key
for the iteratee
)
var array1 = [2.1];
var array2 = [1.2, 2.3];
var result = _.unionBy(array1, array2, Math.floor)
console.log(result)
var array1 = [2.1];
var array2 = [1.2, 2.3];
function unionBy(...arrays) {
const iteratee = (arrays).pop();
if (Array.isArray(iteratee)) {
return [];
}
return [...arrays].flat().filter(
(set => (o) => set.has(iteratee(o)) ? false : set.add(iteratee(o)))(new Set()),
);
};
console.log(unionBy(array1, array2, Math.floor))
Browser Support for Array.prototype.flat()
Browser Support for Array.isArray()
| | | | | |
---|
5.0 ✔ | ✔ | 4.0 ✔ | 9.0 ✔ | 10.5 ✔ | 5.0 ✔ |
Browser Support for Set.prototype.has()
⬆ back to top
Collection*
[!IMPORTANT]
Most native equivalents are array methods,
and will not work with objects. If this functionality is needed and no object method is provided,
then Lodash/Underscore is the better option.
_.each
Iterates over a list of elements, yielding each in turn to an iteratee function.
_.each([1, 2, 3], function (value, index) {
console.log(value)
})
_.each({'one':1, 'two':2, 'three':3}, function(value) {
console.log(value)
})
[1, 2, 3].forEach(function (value, index) {
console.log(value)
})
Object.entries({'one':1, 'two':2, 'three':3}).forEach(function([key,value],index) {
console.log(value)
})
Browser Support for Array.prototype.forEach()
Browser Support for Object.entries().forEach()
⬆ back to top
_.every
Tests whether all elements in the array pass the test implemented by the provided function.
function isLargerThanTen (element, index, array) {
return element >= 10
}
var array = [10, 20, 30]
var result = _.every(array, isLargerThanTen)
console.log(result)
function isLargerThanTen (element, index, array) {
return element >= 10
}
var array = [10, 20, 30]
var result = array.every(isLargerThanTen)
console.log(result)
Browser Support for Array.prototype.every()
⬆ back to top
_.filter
Creates a new array with all elements that pass the test implemented by the provided function.
function isBigEnough (value) {
return value >= 10
}
var array = [12, 5, 8, 130, 44]
var filtered = _.filter(array, isBigEnough)
console.log(filtered)
function isBigEnough (value) {
return value >= 10
}
var array = [12, 5, 8, 130, 44]
var filtered = array.filter(isBigEnough)
console.log(filtered)
Browser Support for Array.prototype.filter()
⬆ back to top
_.groupBy
Group items by key.
var grouped = _.groupBy(['one', 'two', 'three'], 'length')
console.log(grouped)
var grouped = ['one', 'two', 'three'].reduce((r, v, i, a, k = v.length) => ((r[k] || (r[k] = [])).push(v), r), {})
console.log(grouped)
Object.groupBy(['one', 'two', 'three'], ({length}) => length)
var grouped = _.groupBy([1.3, 2.1, 2.4], num => Math.floor(num))
console.log(grouped)
var grouped = [1.3, 2.1, 2.4].reduce((r, v, i, a, k = Math.floor(v)) => ((r[k] || (r[k] = [])).push(v), r), {})
console.log(grouped)
Object.groupBy([1.3, 2.1, 2.4], num => Math.floor(num))
Browser Support for Array.prototype.reduce()
Browser Support for Object.groupBy()
| | | | | |
---|
117.0 ✔ | 117.0 ✔ | 119.0 ✔ | ✖ | 103.0 ✔ | 16.4 ✔ |
⬆ back to top
_.includes
Checks if a value is in collection.
var array = [1, 2, 3]
_.includes(array, 1)
var array = [1, 2, 3]
array.includes(1)
var array = [1, 2, 3]
array.indexOf(1) > -1
Browser Support for Array.prototype.includes
| | | | | |
---|
47.0 ✔ | 14.0 ✔ | 43.0 ✔ | ✖ | 34.0 ✔ | 9.0 ✔ |
Browser Support for Array.prototype.indexOf
⬆ back to top
_.keyBy
[!WARNING]
Not in Underscore.js
Creates an object composed of keys generated from the results of running each element of collection through iteratee.
console.log(_.keyBy(['a', 'b', 'c']))
console.log(_.keyBy([{ id: 'a1', title: 'abc' }, { id: 'b2', title: 'def' }], 'id'))
console.log(_.keyBy({ data: { id: 'a1', title: 'abc' }}, 'id'))
const keyBy = (array, key) => (array || []).reduce((r, x) => ({ ...r, [key ? x[key] : x]: x }), {});
console.log(keyBy(['a', 'b', 'c']))
console.log(keyBy([{ id: 'a1', title: 'abc' }, { id: 'b2', title: 'def' }], 'id'))
console.log(keyBy(Object.values({ data: { id: 'a1', title: 'abc' }}), 'id'))
const collectionKeyBy = (collection, key) => {
const c = collection || {};
return c.isArray() ? keyBy(c, key) : keyBy(Object.values(c), key);
}
Browser Support for Array.prototype.reduce()
| | | | | |
---|
✔ | 12.0 ✔ | 3.0 ✔ | 9.0 ✔ | 10.5 ✔ | 4.0 ✔ |
⬆ back to top
_.map
Translates all items in an array or object to new array of items.
var array1 = [1, 2, 3]
var array2 = _.map(array1, function (value, index) {
return value * 2
})
console.log(array2)
var array1 = [1, 2, 3]
var array2 = array1.map(function (value, index) {
return value * 2
})
console.log(array2)
var object1 = { 'a': 1, 'b': 2, 'c': 3 }
var object2 = _.map(object1, function (value, index) {
return value * 2
})
console.log(object2)
var object1 = { 'a': 1, 'b': 2, 'c': 3 }
var object2 = Object.entries(object1).map(function ([key, value], index) {
return value * 2
})
console.log(object2)
Browser Support for Object.entries()
and destructuring
Browser Support for Array.prototype.map()
⬆ back to top
_.minBy and _.maxBy
Use Array.prototype.reduce()
for find the maximum or minimum collection item
var data = [{ value: 6 }, { value: 2 }, { value: 4 }]
var minItem = _.minBy(data, 'value')
var maxItem = _.maxBy(data, 'value')
console.log(minItem, maxItem)
var data = [{ value: 6 }, { value: 2 }, { value: 4 }]
var minItem = data.reduce(function(a, b) { return a.value <= b.value ? a : b }, {})
var maxItem = data.reduce(function(a, b) { return a.value >= b.value ? a : b }, {})
console.log(minItem, maxItem)
Extract a functor and use es2015 for better code
const makeSelect = (comparator) => (a, b) => comparator(a, b) ? a : b
const minByValue = makeSelect((a, b) => a.value <= b.value)
const maxByValue = makeSelect((a, b) => a.value >= b.value)
const data = [{ value: 6 }, { value: 2 }, { value: 4 }]
const minItem = data.reduce(minByValue, {})
const maxItem = data.reduce(maxByValue, {})
console.log(minItem, maxItem)
const minBy = (collection, key) => {
const select = (a, b) => a[key] <= b[key] ? a : b
return collection.reduce(select, {})
}
console.log(minBy(data, 'value'))
Browser Support for Array.prototype.reduce()
⬆ back to top
_.pluck
array.map
or _.map
can also be used to replace _.pluck
.
Lodash v4.0 removed _.pluck
in favor of _.map
with iteratee shorthand.
Details can be found in Changelog
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = _.pluck(array1, "name")
console.log(names)
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = array1.map(function(x){
return x.name
})
console.log(names)
Browser Support for Array.prototype.map()
⬆ back to top
_.reduce
Applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
var array = [0, 1, 2, 3, 4]
var result = _.reduce(array, function (previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue
})
console.log(result)
var array = [0, 1, 2, 3, 4]
var result = array.reduce(function (previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue
})
console.log(result)
Browser Support for Array.prototype.reduce()
⬆ back to top
_.range
Creates an array of numbers progressing from start up to.
_.range(4)
_.range(-4)
_.range(1, 5)
_.range(0, 20, 5)
Array.from({length: 4}, (_, i) => i)
Array.from({length: 4}, (_, i) => -i)
Array.from({length: 4}, (_, i) => i + 1)
Array.from({length: 4}, (_, i) => i * 5)
[...Array(4).keys()]
[...Array(4).keys()].map(k => -k)
[...Array(4).keys()].map(k => k + 1)
[...Array(4).keys()].map(k => k * 5)
Browser Support for Array.from()
Browser Support for keys and spread in Array literals
| | | | | |
---|
46.0 ✔ | 12.0 ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 7.1 ✔ |
⬆ back to top
_.reduceRight
This method is like _.reduce except that it iterates over elements of collection from right to left.
var array = [0, 1, 2, 3, 4]
var result = _.reduceRight(array, function (previousValue, currentValue, currentIndex, array) {
return previousValue - currentValue
})
console.log(result)
var array = [0, 1, 2, 3, 4]
var result = array.reduceRight(function (previousValue, currentValue, currentIndex, array) {
return previousValue - currentValue
})
console.log(result)
Browser Support for Array.prototype.reduceRight()
⬆ back to top
_.reject
The opposite of _.filter; this method returns the elements of collection that predicate does not return truthy for.
var array = [1, 2, 3, 4, 5];
var result = _.reject(array, function (x) {
return x % 2 === 0;
});
var array = [1, 2, 3, 4, 5];
var reject = function (arr, predicate) {
var complement = function (f) {
return function (x) {
return !f(x);
}
};
return arr.filter(complement(predicate));
};
Browser Support for Array.prototype.filter()
| | | | | |
---|
✔ | 12 ✔ | 1.5 ✔ | 9.0 ✔ | 9.5 ✔ | 3.0 ✔ |
⬆ back to top
_.sample
Gets a random element from array
.
const array = [0, 1, 2, 3, 4]
const result = _.sample(array)
console.log(result)
const array = [0, 1, 2, 3, 4]
const sample = arr => {
const len = arr == null ? 0 : arr.length
return len ? arr[Math.floor(Math.random() * len)] : undefined
}
const result = sample(array)
console.log(result)
Browser Support for Array.prototype.length()
and Math.random()
⬆ back to top
_.size
Returns the number of values in the collection.
var result = _.size({one: 1, two: 2, three: 3})
console.log(result)
var result2 = Object.keys({one: 1, two: 2, three: 3}).length
console.log(result2)
Browser Support for Object.keys()
| | | | | |
---|
5.0 ✔ | ✔ | 4.0 ✔ | 9.0 ✔ | 12.0 ✔ | 5.0 ✔ |
⬆ back to top
_.some
Tests whether any of the elements in the array pass the test implemented by the provided function.
function isLargerThanTen (element, index, array) {
return element >= 10
}
var array = [10, 9, 8]
var result = _.some(array, isLargerThanTen)
console.log(result)
function isLargerThanTen (element, index, array) {
return element >= 10
}
var array = [10, 9, 8]
var result = array.some(isLargerThanTen)
console.log(result)
Browser Support for Array.prototype.some()
⬆ back to top
_.sortBy and _.orderBy
Sorts an array of object based on an object key provided by a parameter (note this is more limited than Underscore/Lodash).
const fruits = [
{name:"banana", amount: 2},
{name:"apple", amount: 4},
{name:"pineapple", amount: 2},
{name:"mango", amount: 1}
];
_.sortBy(fruits, 'name');
_.orderBy(fruits, ['name'],['asc']);
const sortBy = (key) => {
return (a, b) => (a[key] > b[key]) ? 1 : ((b[key] > a[key]) ? -1 : 0);
};
fruits.concat().sort(sortBy("name"));
Browser Support for Array.prototype.concat()
and Array.prototype.sort()
⬆ back to top
_.uniq
Produces a duplicate-free version of the array, using === to test object equality.
var array = [1, 2, 1, 4, 1, 3]
var result = _.uniq(array)
console.log(result)
var array = [1, 2, 1, 4, 1, 3];
var result = [...new Set(array)];
console.log(result)
Browser Support for Spread in array literals
| | | | | |
---|
46.0 ✔ | 12.0 ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 8.0 ✔ |
⬆ back to top
Function
_.after
[!WARNING]
This is an alternative implementation
Creates a version of the function that will only be run after first being called count times. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.
var notes = ['profile', 'settings']
var renderNotes = _.after(notes.length, render)
notes.forEach(function (note) {
console.log(note)
renderNotes()
})
notes.forEach(function (note, index) {
console.log(note)
if (notes.length === (index + 1)) {
render()
}
})
Browser Support for Array.prototype.forEach()
⬆ back to top
_.bind
Create a new function that calls func with thisArg and args.
var objA = {
x: 66,
offsetX: function(offset) {
return this.x + offset;
}
}
var objB = {
x: 67
};
var boundOffsetX = _.bind(objA.offsetX, objB, 0);
var boundOffsetX = objA.offsetX.bind(objB, 0);
Browser Support for Function.prototype.bind()
| | | | | |
---|
7.0 ✔ | ✔ | 4.0 ✔ | 9.0 ✔ | 11.6 ✔ | 5.1 ✔ |
⬆ back to top
_.isFunction
Checks if value is classified as a Function object.
_.isFunction(console.log);
_.isFunction(/abc/);
function isFunction(func) {
return typeof func === "function";
}
isFunction(setTimeout);
isFunction(123);
Browser Support
⬆ back to top
_.debounce
Create a new function that calls func
with thisArg
and args
.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
clearTimeout(timeout);
if (immediate && !timeout) func.apply(context, args);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
};
}
jQuery(window).on('resize', debounce(calculateLayout, 150));
Browser Support for debounce
| | | | | |
---|
7.0 ✔ | ✔ | 4.0 ✔ | 9.0 ✔ | 11.6 ✔ | 5.1 ✔ |
⬆ back to top
_.partial
Create a new function that calls func
with args
.
function greet(greeting, name) {
return greeting + ' ' + name;
}
var sayHelloTo = _.partial(greet, 'Hello');
var result = sayHelloTo('Jose')
console.log(result)
function greet(greeting, name) {
return greeting + ' ' + name;
}
var sayHelloTo = (...args) => greet('Hello', ...args)
var result = sayHelloTo('Jose')
console.log(result)
const partial = (func, ...boundArgs) => (...remainingArgs) => func(...boundArgs, ...remainingArgs)
var sayHelloTo = partial(greet, 'Hello');
var result = sayHelloTo('Jose')
console.log(result)
Browser Support for Spread
| | | | | |
---|
46.0 ✔ | 12.0 ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 8.0 ✔ |
⬆ back to top
_.throttle
Create a new function that limits calls to func
to once every given timeframe.
function throttle(func, timeFrame) {
var lastTime = 0;
return function (...args) {
var now = new Date();
if (now - lastTime >= timeFrame) {
func(...args);
lastTime = now;
}
};
}
jQuery(window).on('resize', throttle(calculateLayout, 150));
Browser Support for throttle
| | | | | |
---|
5.0 ✔ | 12.0 ✔ | 3.0 ✔ | 9.0 ✔ | 10.5 ✔ | 4.0 ✔ |
⬆ back to top
Lang
_.castArray
Puts the value into an array of length one if it is not already an array.
console.log(_.castArray(5))
console.log(_.castArray([2]))
function castArray(arr) {
return Array.isArray(arr) ? arr : [arr]
}
console.log(castArray(5));
console.log(castArray([2]));
Browser Support for Array.isArray()
| | | | | |
---|
5.0 ✔ | ✔ | 4.0 ✔ | 9.0 ✔ | 10.5 ✔ | 5.0 ✔ |
⬆ back to top
_.cloneDeep
Creates a deep copy by recursively cloning the value.
var objects = [{ 'a': 1 }, { 'b': 2 }];
var clone = _.cloneDeep(objects);
console.log(clone[0] === objects[0]);
var objects = [{ 'a': 1 }, { 'b': 2 }];
var clone = structuredClone(objects);
console.log(clone[0] === objects[0]);
Browser Support for structuredClone()
| | | | | |
---|
98.0 ✔ | 98.0 ✔ | 94.0 ✔ | ✖ | 84.0 ✔ | 15.4 ✔ |
⬆ back to top
_.isDate
Checks if value is classified as a Date object.
console.log(_.isDate(new Date));
console.log(Object.prototype.toString.call(new Date) === "[object Date]");
Browser Support for String.prototype.toString.call()
⬆ back to top
_.gt
Checks if value is greater than other.
console.log(_.gt(3, 1))
console.log(3 > 1);
Browser Support
⬆ back to top
_.gte
Checks if value is greater than or equal to other.
console.log(_.gte(3, 1))
console.log(3 >= 1);
Browser Support
⬆ back to top
_.isEmpty
Checks if value is an empty object or collection.
[!WARNING]
The Native version does not support evaluating a Set or a Map
console.log(_.isEmpty(null))
console.log(_.isEmpty(''))
console.log(_.isEmpty({}))
console.log(_.isEmpty([]))
console.log(_.isEmpty({a: '1'}))
const isEmpty = obj => [Object, Array].includes((obj || {}).constructor) && !Object.entries((obj || {})).length;
console.log(isEmpty(null))
console.log(isEmpty(''))
console.log(isEmpty({}))
console.log(isEmpty([]))
console.log(isEmpty({a: '1'}))
Browser Support for Array.prototype.includes()
| | | | | |
---|
47.0 ✔ | 14.0 ✔ | 43.0 ✔ | ✖ | 34.0 ✔ | 9.0 ✔ |
⬆ back to top
_.isFinite
Checks if value is a finite primitive number.
console.log(_.isFinite('3'))
console.log(_.isFinite(3))
console.log(Number.isFinite('3'))
console.log(Number.isFinite(3))
Browser Support for Number.isFinite()
| | | | | |
---|
19.0 ✔ | ✔ | 16.0 ✔ | ✖ | 15.0 ✔ | 9.0 ✔ |
⬆ back to top
_.isInteger
Checks if value is an integer.
console.log(_.isInteger(3))
console.log(_.isInteger('3'))
console.log(Number.isInteger(3))
console.log(Number.isInteger('3'))
Browser Support for Number.isInteger()
⬆ back to top
_.isPlainObject
Checks if value is a plain object, that is, an object created by the Object constructor or one with a [[Prototype]] of null.
var object = { 'a': 1, 'b': 2, 'c': 1 };
var result = _.isPlainObject(object);
console.log(result)
function isPlainObject(value) {
if (typeof value !== 'object' || value === null) return false
if (Object.prototype.toString.call(value) !== '[object Object]') return false
const proto = Object.getPrototypeOf(value);
if (proto === null) return true
const Ctor = Object.prototype.hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (
typeof Ctor === 'function' &&
Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value)
);
}
Browser Support for Object.getPrototypeOf()
| | | | | |
---|
5.0 ✔ | 12.0 ✔ | 3.5 ✔ | ✖ | 12.1 ✔ | 5.0 ✔ |
⬆ back to top
_.isNaN
Checks if a value is NaN.
console.log(_.isNaN(NaN))
console.log(isNaN(NaN))
console.log(Number.isNaN(NaN))
MDN:
In comparison to the global isNaN()
function, Number.isNaN()
doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN
, but aren't actually the same value as NaN
. This also means that only values of the type number, that are also NaN
, return true. Number.isNaN()
Voice from the Lodash author:
Lodash's _.isNaN
is equiv to ES6 Number.isNaN
which is different than the global isNaN
.
--- jdalton
Browser Support for isNaN
Browser Support for Number.isNaN
⬆ back to top
_.isNil
[!WARNING]
Not in Underscore.js
Checks if value is null or undefined.
console.log(_.isNil(null))
console.log(_.isNil(NaN))
console.log(_.isNil(undefined))
console.log(null == null);
console.log(NaN == null);
console.log(undefined == null)
Browser Support
⬆ back to top
_.isNull
Checks if value is null.
console.log(_.isNull(null))
console.log(_.isNull(void 0))
console.log(null === null);
console.log(void 0 === null);
Browser Support
⬆ back to top
_.isUndefined
Checks if value is undefined.
console.log(_.isUndefined(a))
console.log(typeof a === 'undefined');
console.log(a === undefined);
Browser Support
⬆ back to top
Object
_.assign
The method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
function Foo() {
this.c = 3;
}
function Bar() {
this.e = 5;
}
Foo.prototype.d = 4;
Bar.prototype.f = 6;
var result = _.assign(new Foo, new Bar);
console.log(result);
function Foo() {
this.c = 3;
}
function Bar() {
this.e = 5;
}
Foo.prototype.d = 4;
Bar.prototype.f = 6;
var result = Object.assign({}, new Foo, new Bar);
console.log(result);
Browser Support for Object.assign()
| | | | | |
---|
45.0 ✔ | ✔ | 34.0 ✔ | ✖ | 32.0 ✔ | 9.0 ✔ |
⬆ back to top
_.defaults
The method is used to apply new values over an object with default values for keys.
const newValues = {a: 3};
const defaultValues = {a: 1, b: 2}
const appliedValues = _.defaults(newValues, defaultValues);
console.log(appliedValues)
const newValues = {a: 3};
const defaultValues = {a: 1, b: 2}
const appliedValues = Object.assign({}, defaultValues, newValues);
Browser Support for Object.assign()
| | | | | |
---|
45.0 ✔ | ✔ | 34.0 ✔ | ✖ | 32.0 ✔ | 9.0 ✔ |
⬆ back to top
_.extend
The method is used to copy the values of all enumerable own and inherited properties from one or more source objects to a target object.
function Foo() {
this.c = 3;
}
function Bar() {
this.e = 5;
}
Foo.prototype.d = 4;
Bar.prototype.f = 6;
var result = _.extend({}, new Foo, new Bar);
console.log(result);
function Foo() {
this.c = 3;
}
function Bar() {
this.e = 5;
}
Foo.prototype.d = 4;
Bar.prototype.f = 6;
var result = Object.assign({}, new Foo, Foo.prototype, new Bar, Bar.prototype);
console.log(result);
const extend = (target, ...sources) => {
const length = sources.length;
if (length < 1 || target == null) return target;
for (let i = 0; i < length; i++) {
const source = sources[i];
for (const key in source) {
target[key] = source[key];
}
}
return target;
};
console.log(extend({}, new Foo, new Bar));
Browser Support for Object.assign()
| | | | | |
---|
45.0 ✔ | ✔ | 34.0 ✔ | ✖ | 32.0 ✔ | 9.0 ✔ |
⬆ back to top
_.has
Checks if key
is a direct property of object
. Key may be a path of a value separated by .
var object = { a: 1, b: 'settings', c: { d: 'test' } };
var hasA = _.has(object, 'a');
var hasCWhichHasD = _.has(object, 'c.d')
console.log(hasA);
console.log(hasCWhichHasD);
const has = function (obj, key) {
var keyParts = key.split('.');
return !!obj && (
keyParts.length > 1
? has(obj[key.split('.')[0]], keyParts.slice(1).join('.'))
: hasOwnProperty.call(obj, key)
);
};
var object = { a: 1, b: 'settings' };
var result = has(object, 'a');
Browser Support for Object .hasOwnProperty
⬆ back to top
_.get
Gets the value at path of object.
[!NOTE]
If provided path does not exist inside the object js will generate error.
var object = { a: [{ b: { c: 3 } }] };
var result = _.get(object, 'a[0].b.c', 1);
console.log(result);
var object = { a: [{ b: { c: 3 } }] };
var { a: [{ b: { c: result = 1 } = {} } = {}] = [] } = object;
console.log(result);
var object = { a: [{ b: { c: 3 } }] };
var result = object?.a?.[0]?.b?.c ?? 1;
console.log(result);
const get = (obj, path, defaultValue = undefined) => {
const travel = regexp =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
};
var object = { a: [{ b: { c: 3 } }] };
var result = get(object, 'a[0].b.c', 1);
Browser Support for Object destructing
| | | | | |
---|
49.0 ✔ | 14.0 ✔ | 41.0 ✔ | ✖ | 41.0 ✔ | 8.0 ✔ |
Browser Support for optional chaining ?.
| | | | | |
---|
80.0 ✔ | 80.0 ✔ | 74.0 ✔ | ✖ | 67.0 ✔ | 13.1 ✔ |
Browser Support for nullish coalescing operator ??
| | | | | |
---|
80.0 ✔ | 80.0 ✔ | 72.0 ✔ | ✖ | ✖ | 13.1 ✔ |
⬆ back to top
_.invert
Creates an object composed of the inverted keys and values of object. If object contains duplicate values, subsequent values overwrite property assignments of previous values.
var object = { 'a': 1, 'b': 2, 'c': 1 };
var result = _.invert(object);
console.log(result)
function invert(object) {
var obj = {};
for (var key in object) {
if (object.hasOwnProperty(key)) {
obj[object[key]] = key;
}
}
return obj;
}
var result = invert(object);
console.log(result)
const invert = object => Object.entries(object)
.reduce((acc, current) => {
acc[current[1]] = current[0];
return acc;
}, {}
);
Browser Support
| | | | | |
---|
4.0 ✔ | ✔ | 2.0 ✔ | 6.0 ✔ | 10.0 ✔ | 3.1 ✔ |
Browser Support for Object.entries()
| | | | | |
---|
54.0 ✔ | 14.0 ✔ | 47.0 ✔ | ✖ | 41.0 ✔ | 10.1 ✔ |
⬆ back to top
_.keys
Retrieves all the names of the object's own enumerable properties.
var result = _.keys({one: 1, two: 2, three: 3})
console.log(result)
var result2 = Object.keys({one: 1, two: 2, three: 3})
console.log(result2)
Browser Support for Object.keys()
| | | | | |
---|
5.0 ✔ | ✔ | 4.0 ✔ | 9.0 ✔ | 12.0 ✔ | 5.0 ✔ |
⬆ back to top
_.mapKeys
The opposite of _.mapValues; this method creates an object with the same values as object and keys generated by running each own enumerable string keyed property of object thru iteratee. The iteratee is invoked with three arguments: (value, key, object).
var result = _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
return key + value;
});
console.log(result)
function mapKeys(object, cb) {
var obj = {};
for (var key in object) {
if (object.hasOwnProperty(key)) {
var newKey = cb(object[key], key, object);
obj[newKey] = object[key];
}
}
return obj;
}
var result = mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
return key + value;
});
console.log(result)
const mapKeys = (object, cb) => Object.entries(object)
.reduce((acc, current) => {
const newKey = cb(current[1], current[0], object);
acc[newKey] = current[1];
return acc;
}, {}
);
const result2 = mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
return key + value;
});
console.log(result2)
Browser Support
| | | | | |
---|
4.0 ✔ | ✔ | 2.0 ✔ | 6.0 ✔ | 10.0 ✔ | 3.1 ✔ |
Browser Support for Object.entries()
| | | | | |
---|
54.0 ✔ | 14.0 ✔ | 47.0 ✔ | ✖ | 41.0 ✔ | 10.1 ✔ |
⬆ back to top
_.omit
Returns a copy of the object, filtered to omit the keys specified.
var object = { 'a': 1, 'b': '2', 'c': 3 };
var result = _.omit(object, ['a', 'c']);
console.log(result)
var { a, c, ...result2 } = object;
console.log(result2)
Browser Support for Spread in object literals
⬆ back to top
_.pick
Creates an object composed of the object properties predicate returns truthy for.
var object = { 'a': 1, 'b': '2', 'c': 3 };
var result = _.pick(object, ['a', 'c', 'x']);
console.log(result)
function pick(object, keys) {
return keys.reduce((obj, key) => {
if (object && object.hasOwnProperty(key)) {
obj[key] = object[key];
}
return obj;
}, {});
}
var result = pick(object, ['a', 'c', 'x']);
console.log(result)
Browser Support
| | | | | |
---|
38.0 ✔ | ✔ | 13.0 ✔ | 12.0 ✔ | 25.0 ✔ | 7.1 ✔ |
⬆ back to top
_.pickBy
Creates an object composed of the object properties predicate returns truthy for.
var object = { 'a': 1, 'b': null, 'c': 3, 'd': false, 'e': undefined };
var result = _.pickBy(object);
console.log(result)
function pickBy(object) {
const obj = {};
for (const key in object) {
if (object[key]) {
obj[key] = object[key];
}
}
return obj;
}
var result = pickBy(object);
console.log(result)
Browser Support
⬆ back to top
_.toPairs
Retrieves all the given object's own enumerable property [ key, value ]
pairs.
var result = _.toPairs({one: 1, two: 2, three: 3})
console.log(result)
var result2 = Object.entries({one: 1, two: 2, three: 3})
console.log(result2)
Browser Support for Object.entries()
| | | | | |
---|
54.0 ✔ | 14.0 ✔ | 47.0 ✔ | ✖ | 41.0 ✔ | 10.1 ✔ |
⬆ back to top
_.values
Retrieves all the given object's own enumerable property values.
var result = _.values({one: 1, two: 2, three: 3})
console.log(result)
var result2 = Object.values({one: 1, two: 2, three: 3})
console.log(result2)
Browser Support for Object.values()
| | | | | |
---|
54.0 ✔ | 14.0 ✔ | 47.0 ✔ | ✖ | 41.0 ✔ | 10.1 ✔ |
⬆ back to top
String
_.capitalize
[!WARNING]
Not in Underscore.js
Converts the first character of string to upper case and the remaining to lower case.
var result = _.capitalize('FRED');
console.log(result);
const capitalize = (string) => {
return string ? string.charAt(0).toUpperCase() + string.slice(1).toLowerCase() : '';
};
var result = capitalize('FRED');
console.log(result);
Browser Support
⬆ back to top
_.endsWith
[!WARNING]
Not in Underscore.js
Checks if string ends with the given target string.
_.endsWith('abc', 'c');
_.endsWith('abc', 'b');
_.endsWith('abc', 'b', 2);
'abc'.endsWith('c');
'abc'.endsWith('b');
'abc'.endsWith('b', 2);
Browser Support for String.prototype.endsWith()
| | | | | |
---|
41.0 ✔ | ✔ | 17.0 ✔ | ✖ | 28.0 ✔ | 9.0 ✔ |
⬆ back to top
_.isString
Checks if value is classified as a String primitive or object.
_.isString('abc');
_.isString(123);
function isString(str){
if (str != null && typeof str.valueOf() === "string") {
return true
}
return false
}
isString('abc');
isString(123);
Browser Support
⬆ back to top
_.lowerFirst
[!WARNING]
Not in Underscore.js
Converts the first character of string to lower case.
var result = _.lowerFirst('Fred')
console.log(result)
const lowerFirst = (string) => {
return string ? string.charAt(0).toLowerCase() + string.slice(1) : ''
}
var result = lowerFirst('Fred')
console.log(result)
⬆ back to top
_.padStart and _.padEnd
[!WARNING]
Not in Underscore.js
Pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length.
console.log(_.padStart('123', 5, '0'))
console.log(_.padEnd('123', 5, '0'))
console.log('123'.padStart(5, '0'))
console.log('123'.padEnd(5, '0'))
Browser Support for String.prototype.padStart()
and String.prototype.padEnd()
| | | | | |
---|
57.0 ✔ | 15.0 ✔ | 48.0 ✔ | ✖ | 44.0 ✔ | 10.0 ✔ |
⬆ back to top
_.repeat
[!WARNING]
Not in Underscore.js
Repeats the given string n times.
var result = _.repeat('abc', 2)
console.log(result)
var result = 'abc'.repeat(2)
console.log(result)
Browser Support for String.prototype.repeat()
| | | | | |
---|
41.0 ✔ | ✔ | 24.0 ✔ | ✖ | 28.0 ✔ | 9.0 ✔ |
⬆ back to top
_.replace
Returns a new string with some or all matches of a pattern
replaced by a replacement
.
var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var newstr = _.replace(str, re, 'oranges');
console.log(newstr);
var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var result = str.replace(re, 'oranges');
console.log(result);
Browser Support for String.prototype.replace()
⬆ back to top
_.split
[!WARNING]
Not in Underscore.js
Splits string by separator.
var result = _.split('a-b-c', '-', 2)
console.log(result)
var result = 'a-b-c'.split('-', 2)
console.log(result)
Browser Support for String.prototype.split()
⬆ back to top
_.startsWith
[!WARNING]
Not in Underscore.js
Checks if string starts with the given target string.
var result = _.startsWith('abc', 'b', 1)
console.log(result)
var result = 'abc'.startsWith('b', 1)
console.log(result)
Browser Support for String.prototype.startsWith()
| | | | | |
---|
41.0 ✔ | ✔ | 17.0 ✔ | ✖ | 28.0 ✔ | 9.0 ✔ |
⬆ back to top
_.template
[!NOTE]
This is an alternative implementation. Native template literals not escape html.
Create a template function.
const compiled = _.template('hello <%= user %>!');
var result = compiled({ 'user': 'fred' });
console.log(result);
const templateLiteral = (value) => `hello ${value.user}`;
var result = templateLiteral({ 'user': 'fred' });
console.log(result);
Browser Support for String (template) literals
| | | | | |
---|
41.0 ✔ | 12.0 ✔ | 34.0 ✔ | ✖ | 28.0 ✔ | 9.0 ✔ |
⬆ back to top
_.toLower
[!WARNING]
Not in Underscore.js
Lowercases a given string.
var result = _.toLower('FOOBAR')
console.log(result)
var result = 'FOOBAR'.toLowerCase()
console.log(result)
Browser Support for String.prototype.toLowerCase()
⬆ back to top
_.toUpper
[!WARNING]
Not in Underscore.js
Uppercases a given string.
var result = _.toUpper('foobar')
console.log(result)
var result = 'foobar'.toUpperCase()
console.log(result)
Browser Support for String.prototype.toUpperCase()
⬆ back to top
_.trim
[!WARNING]
Not in Underscore.js
Removes the leading and trailing whitespace characters from a string.
var result = _.trim(' abc ')
console.log(result)
var result = ' abc '.trim()
console.log(result)
Browser Support for String.prototype.trim()
| | | | | |
---|
5.0 ✔ | ✔ | 3.5 ✔ | 9.0 ✔ | 10.5 ✔ | 5.0 ✔ |
⬆ back to top
_.upperFirst
[!WARNING]
Not in Underscore.js
Uppercases the first letter of a given string.
var result = _.upperFirst('george')
console.log(result)
const upperFirst = (string) => {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : ''
}
var result = upperFirst('george')
console.log(result)
⬆ back to top
Reference
⬆ back to top
_.uniqWith
Similar to _.uniq
except that it accepts comparator which is invoked to compare elements of array. The order of result values is determined by the order they occur in the array.
const objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
const result = _.uniqWith(objects, _.isEqual);
console.log(result);
const uniqWith = (arr, fn) => arr.filter((element, index) => arr.findIndex((step) => fn(element, step)) === index);
const array = [1, 2, 2, 3, 4, 5, 2];
const result = uniqWith(array, (a, b) => a === b);
console.log(result);
const objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
const result = uniqWith(objects, (a, b) => JSON.stringify(a) === JSON.stringify(b));
console.log(result);
Browser Support for Array.prototype.filter()
and Array.prototype.findIndex()
| | | | | |
---|
45.0 ✔ | 12.0 ✔ | 25.0 ✔ | ✖ | 32.0 ✔ | 8.0 ✔ |
⬆ back to top
Util
_.times
Invokes the iteratee n times, returning an array of the results of each invocation.
var result = _.times(10)
console.log(result)
var result = Array.from({length: 10}, (_,x) => x)
console.log(result)
var result = [...Array(10).keys()]
console.log(result)
Browser Support for Array.from()
⬆ back to top
Number
_.clamp
Clamps number within the inclusive lower and upper bounds.
_.clamp(-10, -5, 5);
_.clamp(10, -5, 5);
_.clamp(10, -5);
_.clamp(10, 99);
const clamp = (number, boundOne, boundTwo) => {
if (!boundTwo) {
return Math.max(number, boundOne) === boundOne ? number : boundOne;
} else if (Math.min(number, boundOne) === number) {
return boundOne;
} else if (Math.max(number, boundTwo) === number) {
return boundTwo;
}
return number;
};
clamp(-10, -5, 5);
clamp(10, -5, 5);
clamp(10, -5);
clamp(10, 99);
Browser Support for Math.min() and Math.max()
⬆ back to top
_.inRange
Checks if n is between start and up to, but not including, end. If end is not specified, it's set to start with start then set to 0. If start is greater than end the params are swapped to support negative ranges.
_.inRange(3, 2, 4);
_.inRange(-3, -2, -6);
const inRange = (num, init, final) => {
if(final === undefined){
final = init;
init = 0;
}
return (num >= Math.min(init, final) && num < Math.max(init, final));
}
const inRange = (num, a, b=0) => (Math.min(a,b) <= num && num < Math.max(a,b));
inRange(3, 2, 4);
inRange(-3, -2, -6);
Browser Support for Math.min() and Math.max()
⬆ back to top
_.random
Produces a random number between the inclusive lower and upper bounds. If only one argument is provided a number between 0 and the given number is returned. If floating is true, or either lower or upper are floats, a floating-point number is returned instead of an integer.
_.random(0, 5);
_.random(5);
_.random(5, true);
_.random(1.2, 5.2);
const random = (a = 1, b = 0) => {
const lower = Math.min(a, b);
const upper = Math.max(a, b);
return lower + Math.random() * (upper - lower);
};
const randomInt = (a = 1, b = 0) => {
const lower = Math.ceil(Math.min(a, b));
const upper = Math.floor(Math.max(a, b));
return Math.floor(lower + Math.random() * (upper - lower + 1))
};
random();
random(5);
random(0, 5);
random(1.2, 5.2);
randomInt();
randomInt(5);
randomInt(0, 5);
randomInt(1.2, 5.2);
Browser Support for Math.random()
⬆ back to top
Inspired by:
License
MIT