10 useful Lodash array functions

January 29, 2019

When working with a lot of data, in many cases you're looking to perform complex operations on arrays of records. This is where Lodash comes in! "A modern JavaScript utility library delivering modularity, performance & extras."

_.chunk(array, [size=1])

Split up an array into chunks of specified sizes.

_.chunk(['d', 'f', 'j', 'k'], 2);
// => [['d', 'f'], ['j', 'k']]

_.compact(array)

Removes all falsey values from an array.

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

_.fill(array, value, [start=0], [end=array.length])

Fill arrays with values.

var array = [1, 2, 3];

_.fill(array, 'b');
console.log(array);
// => ['b', 'b', 'b']

_.fill(Array(4), 5);
// => [5, 5, 5, 5]

_.fill([2, 3, 7, 5], '*', 1, 3);
// => [2, '*', '*', 5]

_.flatten(array)

Flatten an array 1 single level.

_.flatten([6, [8, [2, [1]], 7]]);
// => [6, 8, [2, [1]], 7]

_.flattenDeep(array)

Flatten an array recursively.

_.flattenDeep([6, [8, [2, [1]], 7]]);
// => [6, 8, 2, 1, 7]

_.intersection([arrays])

Gets values that exist in all the arrays provided.

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

_.pull(array, [values])

Removes all instances of provided values from an array.

var array = ['d', 'b', 'f', 'd', 'b', 'f'];

_.pull(array, 'd', 'f');

console.log(array);
// => ['b', 'b']

_.pullAll(array, values)

Removes all instances of provided values from an array. Values provided are inside an array.

var array = ['d', 'b', 'f', 'd', 'b', 'f'];

_.pullAll(array, ['d', 'f']);

console.log(array);
// => ['b', 'b']

_.union([arrays])

Returns an array of unique values that exist in all the arrays provided.

_.union([3], [6, 3]);
// => [3, 6]

_.uniq(array)

Remove duplicates from an array, and get the unique values.

_.uniq([6, 5, 6, 3]);
// => [6, 5, 3]