If you already know the basics of JavaScript arrays, it’s time to take your skills to the next level with more advanced topics. In this tutorial series, you’ll explore intermediate-level topics for programming with arrays in JavaScript.
While there are some useful methods for working with arrays in JavaScript, sometimes they aren’t enough to meet all of our needs. You can save a lot of time by using a library like Lodash which offers a huge set of methods that implement common features missing in native JavaScript methods.
In this tutorial, I’ll show you some cool methods defined in Lodash that you can start using right away. All you have to do to get started is upload the library to your project from any CDN.
Split an array into pieces
You can use the chunk()
method for splitting the array into smaller blocks, each of which will contain the specified number of elements. This grouping of elements occurs from left to right. Sometimes, the array cannot be split evenly and in this case the final block will contain the remaining elements.
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 for shuffling arrays, but there is currently no such method in JavaScript. While writing your own shuffle function isn’t difficult, you can also use the shuffle()
method in Lodash for randomizing 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’s important to remember that this method returns an array of scrambled values. This means that while you can call it on an object, you will just get an array of shuffled values 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
Performing a variety of operations on an array can sometimes result in unwanted false values being filled. You may also get such an array from some other 3rd party service. For example, say you need 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 false values it includes false
, null
, undefined
NaN, the empty 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()
The 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. Note that none of these methods modify the original array.
You probably already know that the native slice()
The method in JavaScript achieves the same thing as drop()
AND dropRight()
methods when the correct parameters are supplied. A little difference between them is that drop()
AND dropRight()
return undefined
when working with empty array slots. This is important to remember when 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 items, you want to remove items from both ends 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 continue to discard values as long as that callback function returns a true 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, the negative values have been stripped from the start and end of the array in the respective function calls. It is also possible to remove all negative values from our array using the remove()
method. However, you should remember that this method mutates the original array while returning a new array with the values removed.
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 you have a bunch of random words stored in an array and you want to pull just a list of unique words from that array. What are you doing? You can use the uniq()
method to do it quickly. The array you get will contain only 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 whether the value under consideration is unique or not. This method accepts a file iteratee
as the second parameter which is basically a function that is invoked for each element. You can also pass a property to evaluate for each element.
Here is an example that considers the length of the words to be the primary factor in determining the uniqueness of the item.
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']
|
Find the difference between two arrays
Finding the difference between two arrays allows you to filter out all elements in the other arrays. This can be useful in a variety of situations such as team selection or color palettes where you don’t want any overlap between colors.
THE difference()
Lodash’s method 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 the 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()
which allows you to calculate the difference between two arrays. However, it offers additional control over how values are compared. You can pass a callback function to the file differenceBy()
method that will be called 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()
The method eliminated all elements with a name match instead of a full match. Since then, we’ve had a “Joe Adams” in the array team_a
THE team_c
array even eliminated “Joe Baker” when 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 into smaller arrays of a specific size. There is another method called groupBy()
which you can use to group different elements of any array.
This method takes a callback function as a second parameter that sets the criteria for grouping the elements. Returns an object whose keys are the values generated by the callback and whose values are the array elements that 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 |
"Thurs": [
|
23 |
"Joe Baker",
|
24 |
"Joe Miller"
|
25 |
],
|
26 |
"Rakesh": [
|
27 |
"Rakesh Sharma"
|
28 |
],
|
29 |
"Want": [
|
30 |
"Will Smith",
|
31 |
"Will Bateman"
|
32 |
],
|
33 |
"Samantha": [
|
34 |
"Samantha Garcia"
|
35 |
]
|
36 |
}
|
37 |
|
38 |
*/
|
Final thoughts
This tutorial has covered some useful methods in the Lodash library that you can use to manipulate arrays. The library was immensely useful when it was first released due to its large list of very useful methods. It still provides some decent functionality, but JavaScript standards have also improved a lot over 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’ll use in your code.
Post thumbnail generated with OpenAI’s DALL-E 2.