Skip to content

Latest commit

 

History

History
544 lines (400 loc) · 14.4 KB

Dont-Need-Lodash-Underscore.md

File metadata and controls

544 lines (400 loc) · 14.4 KB

Quick Links

Array

  1. _.chunk
  2. _.compact
  3. _.concat
  4. _.fill
  5. _.find
  6. _.findIndex
  7. _.first
  8. _.flatten
  9. _.flattenDeep
  10. _.fromPairs
  11. _.head and _.tail
  12. _.indexOf
  13. _.join
  14. _.last
  15. _.lastIndexOf
  16. _.reverse
  17. _.without
  18. _.slice
  19. _.isArray
  20. _.isArrayBuffer

Collection*

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.

  1. _.each
  2. _.every
  3. _.filter
  4. _.groupBy
  5. _.includes
  6. _.map
  7. _.minBy and _.maxBy
  8. _.orderBy
  9. _.pluck
  10. _.range
  11. _.reduce
  12. _.reduceRight
  13. _.size
  14. _.some
  15. _.sortBy
  16. _.uniq

Function

  1. _.after
  2. _.bind
  3. _.partial

Lang

  1. _.isNaN
  2. _.isUndefined
  3. _.gt
  4. _.gte

Object

  1. _.assign
  2. _.keys
  3. _.toPairs
  4. _.values
  5. _.get
  6. _.omit

String

  1. _.repeat
  2. _.template
  3. _.toLower
  4. _.toUpper
  5. _.trim
  6. _.replace

Array

_.chunk

Creates an array of elements split into groups the length of size.

// Underscore/Lodash
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]


// Native

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);
// => [['a', 'b'], ['c', 'd']]

chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

Browser Support

Chrome Firefox IE Opera Safari
Not Supported

⬆ back to top

_.compact

Creates an array with all falsy values removed.

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

// Native
[0, 1, false, 2, '', 3].filter(Boolean)

Browser Support

Chrome Firefox IE Opera Safari
1.5 ✔ 9 ✔

⬆ back to top

_.concat

Creates a new array concatenating array with any additional arrays and/or values.

// Underscore/Lodash
var array = [1]
var other = _.concat(array, 2, [3], [[4]])

console.log(other)
// output: [1, 2, 3, [4]]

// Native
var array = [1]
var other = array.concat(2, [3], [[4]])

console.log(other)
// output: [1, 2, 3, [4]]

Browser Support

Chrome Firefox IE Opera Safari
1.0 ✔ 1.0 ✔ 5.5 ✔

⬆ back to top

⬆ back to top

_.find

Returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

// Underscore/Lodash
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; })
// output: object for 'barney'

// Native
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; })
// output: object for 'barney'

Browser Support

Chrome Firefox IE Opera Safari
45.0 ✔ 25.0 ✔ Not supported 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.

// Underscore/Lodash
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)
// output: 1

// Native
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)
// output: 1

Browser Support

Chrome Firefox IE Opera Safari
45.0 ✔ 25.0 ✔ Not supported 32.0 ✔ 7.1 ✔

⬆ back to top

_.fromPairs

Returns an object composed from key-value pairs.

// Underscore/Lodash
_.fromPairs([['a', 1], ['b', 2]]);
// => { 'a': 1, 'b': 2 }

// Native
const fromPairs = function(arr) {
  return arr.reduce(function(accumulator, value) {
    accumulator[value[0]] = value[1];
    return accumulator;
  }, {})
}

// Compact form
const fromPairs = (arr) => arr.reduce((acc, val) => (acc[val[0]] = val[1], acc), {})

fromPairs([['a', 1], ['b', 2]]);
// => { 'a': 1, 'b': 2 }

Browser Support

Chrome Firefox IE Opera Safari
3.0 ✔ 9 ✔ 10.5 ✔ 4.0 ✔

⬆ back to top

Collection*

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.

_.groupBy

Group items by key.

// Underscore/Lodash
var grouped = _.groupBy(['one', 'two', 'three'], 'length')
console.log(grouped)
// output: {3: ["one", "two"], 5: ["three"]}

// Native
var grouped = ['one', 'two', 'three'].reduce((r, v, i, a, k = v.length) => ((r[k] || (r[k] = [])).push(v), r), {})
console.log(grouped)
// output: {3: ["one", "two"], 5: ["three"]}
// Underscore/Lodash
var grouped = _.groupBy([1.3, 2.1, 2.4], num => Math.floor(num))
console.log(grouped)
// output: {1: [1.3], 2: [2.1, 2.4]}

// Native
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)
// output: {1: [1.3], 2: [2.1, 2.4]}

Browser Support

Chrome Firefox IE Opera Safari
3.0 ✔ 9 ✔ 10.5 ✔ 4.0 ✔

_.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

// Underscore/Lodash
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = _.pluck(array1, "name")
console.log(names)
// output: ["Alice", "Bob", "Jeremy"]

// Native
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = array1.map(function(x){
  return x.name
})
console.log(names)
// output: ["Alice", "Bob", "Jeremy"]

Browser Support

Chrome Firefox IE Opera Safari
1.5 ✔ 9 ✔

⬆ 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}
];

// Underscore
_.sortBy(fruits, 'name');
// => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]

// Lodash
_.orderBy(fruits, ['name'],['asc']);
// => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]

// Native
const sortBy = (key) => {
  return (a, b) => (a[key] > b[key]) ? 1 : ((b[key] > a[key]) ? -1 : 0);
};

fruits.sort(sortBy("name"));
// => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]

Function

_.partial

Create a new function that calls func with args.

// Lodash
function greet(greeting, name) {
  return greeting + ' ' + name;
}
var sayHelloTo = _.partial(greet, 'hello');

// Native
function greet(greeting, name) {
  return greeting + ' ' + name;
}
var sayHelloTo = (...args) => greet('hello', ...args)

Browser Support

Chrome Firefox IE Opera Safari
62 ✔ 56 ✔ 49 ✔ 11 ✔

⬆ back to top

Lang

_.isNaN

Checks if a value is NaN.

// Underscore/Lodash
console.log(_.isNaN(NaN))
// output: true

// Native
console.log(isNaN(NaN))
// output: true

// ES6
console.log(Number.isNaN(NaN))
// output: true

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

Chrome Firefox IE Opera Safari

Browser Support for Number.isNaN

Chrome Firefox IE Opera Safari
25 ✔ 15 ✔ Not supported 9 ✔

⬆ back to top

_.gt

Checks if value is greater than other.

// Lodash
console.log(_.gt(3, 1))
// output: true

// Native
console.log(3 > 1);
// output: true

Browser Support

Chrome Firefox IE Opera Safari

⬆ back to top

_.toPairs

Retrieves all the given object's own enumerable property [ key, value ] pairs.

// Underscore - also called _.pairs
// Lodash - also called _.entries
var result = _.toPairs({one: 1, two: 2, three: 3})
console.log(result)
// output: [["one", 1], ["two", 2], ["three", 3]]

// Native
var result2 = Object.entries({one: 1, two: 2, three: 3})
console.log(result2)
// output: [["one", 1], ["two", 2], ["three", 3]]

Browser Support

Chrome Firefox IE Opera Safari
38 ✔ 28 ✔ Not supported 25 ✔ 7.1 ✔

⬆ back to top

_.get

Gets the value at path of object. Note: If provided path does not exists inside the object js will generate error.

// Lodash
var object = { a: [{ b: { c: 3 } }] };
var result = _.get(object, 'a[0].b.c', 1);
console.log(result);
// output: 3

// Native
var object = { a: [{ b: { c: 3 } }] };
var { a: [{ b: { c: result2 = 1 } }] } = object;
console.log(result2);
// output: 3

Browser Support

Chrome Firefox IE Opera Safari
49 ✔ 41 ✔ Not supported 41.0 ✔ 8 ✔

String

_.repeat

Lodash only Repeats the given string n times.

// Lodash
var result = _.repeat('abc', 2)
// output: 'abcabc'

// Native
var result = 'abc'.repeat(2)
console.log(result)
// output: 'abcabc'

Browser Support

Chrome Firefox IE Opera Safari
41 ✔ 24 ✔ Not supported 28 ✔ 9 ✔

⬆ back to top

Reference