Arrays are one of the fundamental building blocks of most programming languages. Learning to work with arrays will make your job much easier. In this tutorial we’ll learn all about filtering arrays in JavaScript.
Filtering arrays is something you’ll find yourself doing almost every day as a developer. Luckily, JavaScript has a powerful method to make filtering arrays easy and accessible. The method is aptly named filter()
and in this post, we’ll learn how to get the most out of it.
JavaScript filter()
Method
The filter()
method is a built-in function that can be run on any Array in JavaScript. The filter()
method takes in a single parameter which is a callback function. This callback function then takes in anywhere from one to three parameters. Calling the filter()
method on an array, produces a new array with filtered values based on user defined criteria. Let’s see how this works in practice.
// We'll start with an array of friends
const friends = ['Megan', 'Chris', 'Sarah', 'James', 'Sam', 'Ryan', 'Brad']
// We want to filter out friends with more than 4 letters in their name
const results = friends.filter(function (name) {
if (name.length < 5) {
return true
}
})
console.log(results) // ["Sam", "Ryan", "Brad"]
Thanks to ES6, we can greatly simplify this code though:
// We'll start with an array of friends
const friends = ['Megan', 'Chris', 'Sarah', 'James', 'Sam', 'Ryan', 'Brad']
// ES6 Syntax
const results = friends.filter((name) => name.length < 5)
console.log(results) // ["Sam", "Ryan", "Brad"]
When using the filter()
method, the callback function gets called once for each item in the array. If the return value for the callback function is true
, then the item will be added in the new array, and if the return value is false
, the item evaluated will not be added to the new array.
JavaScript filter()
Method with Objects
Let’s take a look at another example. This time we’ll filter an array of objects. Let’s suppose we have an array of objects that represent our friends with some additional information about each friend. We’ll store the friends gender and occupation. For our filter, we’ll only want to display friends that are female and work as an author.
// Friends array
const friends = [
{name: 'Megan', gender: 'Female', occupation: 'Author'},
{name: 'Chris', gender: 'Male', occupation: 'Developer'},
{name: 'Sarah', gender: 'Female', occupation: 'Developer'},
{name: 'Edvina', gender: 'Female', occupation: 'Student'},
]
const results = friends.filter(
(friend) => friend.gender === 'Female' && friend.occupation == 'Author',
)
console.log(results) // { name: "Megan", gender: "Female", occupation: "Author"}
JavaScript filter()
Method Additional Properties
In the introduction, I mentioned that the callback function for the filter()
method takes in a variable number of parameters ranging from one to three. In our examples so far, the callback function has only taken one parameter, which contained the value of the element in the array at that index. The filter()
callback function can take in two additional parameters. The two additional parameters are the index of the current element and the array itself.
Putting all this together, we can see that the signature of the callback function is function(value, index, array)
. But why would we care about the index and the array values? One good use case is updating the original array. Remember that when we call the filter()
method we are getting back a new array with our filtered out values. But let’s say we wanted to update the original array. How would we do it? Let’s take a look.
Let’s assume we have an array with scores. The issue is that somewhere outside of our control the scores are populated as either a number or a string containing the number. We want to update our array so that all the values are of type number. Here is how I would do it:
// Our array of scores
const scores = [30, 25, '20', 15, 40, '25']
// We're not assigning the value of the filter to any variable
scores.filter((score, i, arr) => {
// Check if the type of score is not a number.
if (!isNaN(score)) {
// Update the original scores array at the right index with the right value
arr[i] = parseInt(score)
}
})
console.log(scores) //[30, 25, 20, 15, 40, 25]
There are other times where having the index and access to the entire array are useful, and if you only need the index, you don’t have to pass in the whole array.
Summary
Today we learned about the filter()
method available to all JavaScript arrays. The filter()
method is a powerful tool allowing us to easily filter out elements in the array based on whatever criteria we desire. Typically when the filter()
method is used, we’ll create a new array to store our filtered values, but by using the optional parameters, we can update an existing array as well.
Happy hacking.