Shuffle the elements of an Array
shuffle()
method in Lodash to randomize the elements in an array.
let people = ["Jane", "Adam", "Nitish", "Joe", "Rakesh", "Will", "Andrew", "Samantha"];
console.log(_.shuffle(people));
// outputs: ['Joe', 'Samantha', 'Adam', 'Jane', 'Andrew', 'Rakesh', 'Will', 'Nitish']
Remove falsey values from an Array
compact()
method to filter out all the falsey values, including false, null, undefined, NaN, the empty string "", and 0. Here is an example:
let values = ["Chilly", "Sunny", undefined, '', "Sunny", false, "Cloudy"];
console.log(_.compact(values));
// Outputs: ['Chilly', 'Sunny', 'Sunny', 'Cloudy']
Difference between two Arrays
The
difference()
method from Lodash will return a new array that contains all the values from the first array that are not part of the second array.
let people = ["Adam", "Nitish", "Joe", "Rakesh", "Will", "Andrew", "Samantha"];
let team_a = ["Adam", "Andrew", "Jane", "Samantha"];
let team_b = _.difference(people, team_a);
console.log(team_b);
// Outputs: ['Nitish', 'Joe', 'Rakesh', 'Will']
Compose object from key-value pairs
The inverse of
_.toPairs()
this method returns an object composed from key-value pairs.
_.fromPairs([['a', 1], ['b', 2]]);
// => { 'a': 1, 'b': 2 }
Grouping Array elements together
The
_.groupBy()
can use to group different elements of any array.
_.groupBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': [4.2], '6': [6.1, 6.3] }
Deep comparison between two values
Performs a deep comparison between two values to determine if they are equivalent.
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
Top comments (0)