Tuesday, February 21, 2023

Useful Methods for Arrays in the Lodash Library

Useful Methods for Arrays in the Lodash Library

If you already understand the basics of JavaScript arrays, it's time to take your skills to the next level with more advanced topics. In this series of tutorials, you'll explore intermediate-level topics for programming with arrays in JavaScript.

While there are quite a few useful methods to work with Arrays in JavaScript, they are sometimes not enough to meet all our needs. You can save a lot of time by using a library like Lodash that offers a huge set of methods that implement common functionality missing from native JavaScript methods.

In this tutorial, I will show you some interesting methods defined in Lodash that you can start using right away. All you need to do to get started is load the library in your project from any CDN.

Task Lodash Methods
split an array into chunks _.chunk()
shuffle the elements of an array _.shuffle()
remove falsey values from an array _.compact
removing elements from an array

_.drop(), _.dropRight(), _.dropWhile(), _.dropRightWhile()

finding unique array elements _.uniq(), _.uniqby()
finding the difference between two arrays _.difference(), _.differenceBy()
grouping array elements together _.groupBy()

Split an Array Into Chunks

You can use the chunk() method to split your array into smaller chunks each of which will contain the specified number of elements. This grouping of elements happens from left to right. Sometimes, the array can't be split evenly and the final chunk will contain the remaining elements in this case.

1
let people = ["Jane", "Adam", "Nitish", "Joe", "Rakesh", "Will", "Andrew", "Samantha"];
2
3
console.log(_.chunk(people, 3));
4
/* Outputs:

5


6
[['Jane', 'Adam', 'Nitish'], ['Joe', 'Rakesh', 'Will'], ['Andrew', 'Samantha']]

7


8
*/

Shuffle the Elements of an Array

PHP has a built-in method to shuffle arrays but no such method currently exists in JavaScript. While writing your own shuffle function isn't hard, you can also use the shuffle() method in Lodash to randomize the elements in an array.

1
let people = ["Jane", "Adam", "Nitish", "Joe", "Rakesh", "Will", "Andrew", "Samantha"];
2
3
console.log(_.shuffle(people));
4
// outputs: ['Joe', 'Samantha', 'Adam', 'Jane', 'Andrew', 'Rakesh', 'Will', 'Nitish']

It is important to remember that this method returns an array of shuffled values. This means that while you can call it on an object, you will only get an array of shuffled values back as shown below:

1
let country_capitals = {
2
  "India": "Delhi",
3
  "China": "Beijing",
4
  "Germany": "Berlin",
5
  "France": "Paris"
6
}
7
8
console.log(_.shuffle(country_capitals));
9
// Outputs: ['Paris', 'Beijing', 'Berlin', 'Delhi']

Remove Falsey Values From an Array

Doing a variety of operations on an array can sometimes result in it being filled with undesired falsey values. You might also receive such an array from some other third party service. For example, let's say you are supposed to get weather information from different places stored in an array and some of the returned values are undefined, false or an empty string etc.

In these cases, you can use the compact() method to filter out all the falsey values which includes false, null, undefined, NaN, the emptry string "", and 0. Here is an example:

1
let values = ["Chilly", "Sunny", undefined, '', "Sunny", false, "Cloudy"];
2
3
console.log(_.compact(values));
4
// Outputs: ['Chilly', 'Sunny', 'Sunny', 'Cloudy']

Removing Elements From an Array

There are a variety of methods in Lodash that can help you remove elements from an array. The drop() method allows you to remove a specific number of elements from the beginning of the array. On the other hand, the dropRight() method allows you to remove a specific number of elements from the end of the array. Please note that neither of these methods mutate the original array.

You are probably already know that the native slice() method in JavaScript achieves the same thing as drop() and dropRight() methods when supplied the right parameters. One minor difference between them is that drop() and dropRight() return undefined when working with empty array slots. This is important to remember when you are working with array methods like map(). Here is an example:

1
let numbers = new Array(10);
2
_.fill(numbers, 5, 3, 6);
3
4
console.log(numbers)
5
// Outputs: [empty × 3, 5, 5, 5, empty × 4]

6
7
console.log(numbers.slice(2));
8
// Outputs: [empty, 5, 5, 5, empty × 4]

9
10
console.log(_.drop(numbers, 2));
11
// Outputs: [undefined, 5, 5, 5, undefined, undefined, undefined, undefined]

12
13
console.log(numbers.slice(0, -2));
14
// Outputs: [empty × 3, 5, 5, 5, empty × 2]

15
16
console.log(_.dropRight(numbers, 2));
17
// Outputs: [undefined, undefined, undefined, 5, 5, 5, undefined, undefined]

What if instead of removing a fixed number of elements, you want to remove elements from either end that don't meet a particular criteria? You can consider using the dropWhile() and dropRightWhile() methods in this case. They accept a callback function and keep dropping values as long as that callback function returns a truthy value.

1
function is_negative(num) {
2
  return num < 0;
3
}
4
5
let numbers = [-2, -5, 8, 3, 42, -63, 2, -1, -34];
6
7
console.log(_.dropWhile(numbers, is_negative));
8
// Outputs: [8, 3, 42, -63, 2, -1, -34]

9
10
console.log(_.dropRightWhile(numbers, is_negative));
11
// outputs: [-2, -5, 8, 3, 42, -63, 2]

As you can see negative values were removed from the beginning and the end of the array in respective function calls. It is also possible to remove all the negative values from our array by using the remove() method. However, you should remember that this method mutates the original array while returning a new array with the removed values.

1
function is_negative(num) {
2
  return num < 0;
3
}
4
5
let numbers = [-2, -5, 8, 3, 42, -63, 2, -1, -34];
6
7
let negatives = _.remove(numbers, is_negative);
8
9
console.log(numbers);
10
// Outputs: [8, 3, 42, 2]

11
12
console.log(negatives);
13
// outputs: [-2, -5, -63, -1, -34]

Finding Unique Array Elements

Let's say that you have a bunch of random words stored in an array and you want to only extract a list of unique words from that array. What do you do? You can use the uniq() method to get it done quickly. The array that you get back will only contain the first occurrence of each repeating element. The elements in the new array will also be in their original order.

1
let words = ["copy", "proof", "legal", "proof", "first", "above", "first", "taxation", "result", "relief", "version", "order", "order", "result", "copy", "fire", "pudding", "anyway"];
2
3
console.log(_.uniq(words));
4
// Outputs: ['copy', 'proof', 'legal', 'first', 'above', 'taxation', 'result', 'relief', 'version', 'order', 'fire', 'pudding', 'anyway']

Another variation of this method is uniqBy() which will allow you to define the criteria used to determine if the value under consideration is unique or not. This method accepts an iteratee as its second parameter which is basically a function that is invoked for every element. You can also pass a property to be evaluated for each element.

Here is an example that considers the length of words to be the primary factor when determining the uniqueness of the element.

1
let words = ["copy", "proof", "legal", "proof", "first", "above", "first", "taxation", "result", "relief", "version", "order", "order", "result", "copy", "fire", "pudding", "anyway"];
2
3
console.log(_.uniqBy(words, 'length'));
4
// Outputs: ['copy', 'proof', 'taxation', 'result', 'version']

Finding the Difference Between Two Arrays

Finding the difference between two arrays allows you to filter out any elements that are present in the other arrays. This can be useful in a variety of situations such as selecting teams or color pallets where you don't want any overlap between colors.

The difference() method from Lodash allows you to do exactly that. It will return a new array that contains all the values from the first array that are not part of the second array. The order of returned values will be determined by the first array. Here is an example:

1
let people = ["Adam", "Nitish", "Joe", "Rakesh", "Will", "Andrew", "Samantha"];
2
3
let team_a = ["Adam", "Andrew", "Jane", "Samantha"];
4
let team_b = _.difference(people, team_a);
5
6
console.log(team_b);
7
// Outputs: ['Nitish', 'Joe', 'Rakesh', 'Will']

There is another method called differenceBy() that allows you to calculate the difference between two arrays. However, it gives you additional control over the way in which the values are compared. You can pass a callback function to the differenceBy() method which will be invoked for all elements to determine how they should be compared. Here is an example:

1
function first_name(full_name) {
2
  return full_name.split(' ')[0];
3
}
4
5
let people = ["Adam Brown", "Nitish Kumar", "Andrew Jones", "Joe Baker", "Rakesh Sharma", "Will Smith", "Joe Miller", "Andrew Blackman", "Samantha Garcia"];
6
7
let team_a = ["Adam Brown", "Andrew Jones", "Jane Miller", "Joe Adams"];
8
9
let team_b = _.difference(people, team_a);
10
let team_c = _.differenceBy(people, team_a, first_name);
11
12
console.log(team_b);
13
// Outputs: ['Nitish Kumar', 'Joe Baker', 'Rakesh Sharma', 'Will Smith', 'Joe Miller', 'Andrew Blackman', 'Samantha Garcia']

14
15
console.log(team_c);
16
// Outputs: ['Nitish Kumar', 'Rakesh Sharma', 'Will Smith', 'Samantha Garcia']

As you can see, when we used our custom function to evaluate the values for comparison, the returned array with the differenceBy() method dropped all elements with a first name match instead of complete match. Since, we had a "Joe Adams" in the array team_a, the team_c array even dropped "Joe Baker" while calculating the difference.

Grouping Array Elements Together

At the beginning of this tutorial, we learned how the chunk() method can be used to split an array in smaller arrays of specific size. There is another method called groupBy() that you can use to group together different elements of any array.

This method accepts a callback function as its second parameter which sets the criteria for grouping the elements. It gives back an object whose keys are the values generated by the callback and whose values are the array elements which generated those keys. Here is an example:

1
function first_name(full_name) {
2
  return full_name.split(' ')[0];
3
}
4
5
let people = ["Adam Brown", "Nitish Kumar", "Andrew Jones", "Joe Baker", "Rakesh Sharma", "Will Smith", "Joe Miller", "Andrew Blackman", "Samantha Garcia", "Will Bateman", "Adam Davis"];
6
7
console.log(_.groupBy(people, first_name));
8
/* Outputs:

9


10
{

11
    "Adam": [

12
        "Adam Brown",

13
        "Adam Davis"

14
    ],

15
    "Nitish": [

16
        "Nitish Kumar"

17
    ],

18
    "Andrew": [

19
        "Andrew Jones",

20
        "Andrew Blackman"

21
    ],

22
    "Joe": [

23
        "Joe Baker",

24
        "Joe Miller"

25
    ],

26
    "Rakesh": [

27
        "Rakesh Sharma"

28
    ],

29
    "Will": [

30
        "Will Smith",

31
        "Will Bateman"

32
    ],

33
    "Samantha": [

34
        "Samantha Garcia"

35
    ]

36
}

37


38
*/

Final Thoughts

This tutorial covered some useful methods in the Lodash library that you can use to manipulate arrays. The library was immensely helpful when it was first released due to its extensive list of very useful methods. It still provides some decent functionality but JavaScript standards have also improved a lot with time.

Some of the original functionality implemented in the library is now available natively in JavaScript. However, you can still get the best of both worlds by selectively loading the methods you will use in your code.

Post thumbnail generated with OpenAI's DALL-E 2.


No comments:

Post a Comment