You don't (may not) need Lodash/Underscore
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 of the functions, Lodash provides you more options than native built-ins. This list is not a 1:1 comparison.
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
"plugins": ["you-dont-need-lodash-underscore"],
"extend" : ["you-dont-need-lodash-underscore:compatible"],
For more information, see Configuring the ESLint Plugin
Quick Links
Array
- _.compact
- _.concat
- _.fill
- _.find
- _.findIndex
- _.indexOf
- _.join
- _.lastIndexOf
- _.reverse
- _.without
Collection*
:heavy_exclamation_mark:Important: Note that the native equivalents are array methods,
and will not work with objects. If this functionality is needed,
then Lodash/Underscore is the better option.
- _.each
- _.every
- _.filter
- _.includes
- _.map
- _.pluck
- _.reduce
- _.reduceRight
- _.size
- _.some
- _.minBy and _.maxBy
Function
- _.after
Lang
- _.isNaN
Object
- _.assign
- _.keys
- _.values
- _.toPairs
String
- _.repeat
- _.toLower
- _.toUpper
- _.trim
- _.template
Array
_.compact
Creates an array with all falsey values removed.
_.compact([0, 1, false, 2, '', 3]);
[0, 1, false, 2, '', 3].filter( v => !!v)
Browser Support
⬆ 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
⬆ back to top
_.fill
Fills elements of array with value from start up to, but not including, end.
Note that 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
| | | | |
---|
45.0 ✔ | 31.0 ✔ | Not supported | Not supported | 7.1 ✔ |
⬆ 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
| | | | |
---|
45.0 ✔ | 25.0 ✔ | Not supported | Not supported | 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
| | | | |
---|
45.0 ✔ | 25.0 ✔ | Not supported | Not supported | 7.1 ✔ |
⬆ 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
⬆ back to top
_.join
:heavy_exclamation_mark:Lodash only
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
⬆ 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
⬆ back to top
_.reverse
:heavy_exclamation_mark:Lodash only
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
⬆ back to top
_.without
:heavy_exclamation_mark:Lodash only
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
⬆ back to top
Collection*
:heavy_exclamation_mark:Important: Note that the native equivalents are array methods,
and will not work with objects. If this functionality is needed,
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)
})
[1, 2, 3].forEach(function (value, index) {
console.log(value)
})
Browser Support
⬆ 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
⬆ 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
⬆ 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 ✔ | 43 ✔ | Not supported | 34 ✔ | 9 ✔ |
Browser Support for Array.prototype.indexOf
⬆ 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)
_.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
⬆ 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
⬆ 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
⬆ 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
⬆ 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
⬆ back to top
_.minBy and _.maxBy
Use Array#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))
Browser Support
⬆ back to top
Function
_.after
:heavy_exclamation_mark:Note 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
⬆ back to top
Lang
_.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
| | | | |
---|
25 ✔ | 15 ✔ | Not supported | ✔ | 9 ✔ |
⬆ 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
| | | | |
---|
45 ✔ | 34 ✔ | No support | 32 ✔ | 9 ✔ |
⬆ 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
⬆ 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
| | | | |
---|
54 ✔ | 47 ✔ | Not supported | Not supported | Not supported |
⬆ 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
| | | | |
---|
38 ✔ | 28 ✔ | Not supported | 25 ✔ | 7.1 ✔ |
⬆ back to top
String
_.repeat
:heavy_exclamation_mark:Lodash only
Repeats the given string n times.
var result = _.repeat('abc', 2)
var result = 'abc'.repeat(2)
console.log(result)
Browser Support
| | | | |
---|
41 ✔ | 24 ✔ | Not supported | Not supported | 9 ✔ |
⬆ back to top
_.toLower
:heavy_exclamation_mark:Lodash only
Lowercases a given string.
var result = _.toLower('FOOBAR')
console.log(result)
var result = 'FOOBAR'.toLowerCase()
console.log(result)
Browser Support
⬆ back to top
_.toUpper
:heavy_exclamation_mark:Lodash only
Uppercases a given string.
var result = _.toUpper('foobar')
console.log(result)
var result = 'foobar'.toUpperCase()
console.log(result)
Browser Support
⬆ back to top
_.trim
:heavy_exclamation_mark:Lodash only
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
| | | | |
---|
5.0 ✔ | 3.5 ✔ | 9.0 ✔ | 10.5 ✔ | 5.0 ✔ |
⬆ back to top
_.template
:heavy_exclamation_mark: Note this is an alternative implementation. Native template literals not escape html.
Create a template function.
const compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
const templateLitreal = (value) => `hello ${value.user}`;
templateLiterlFunction({ 'user': 'fred' });
Browser Support
| | | | |
---|
41 ✔ | 34 ✔ | Not supported | 28 ✔ | 9 ✔ |
⬆ back to top
Reference
Inspired by:
License
MIT