In this and the next few lessons, you'll review some handy array methods which will help you manipulate arrays in JavaScript in a functional style.
There are many array methods, and all of them have their uses. In this lesson, you will see one of them in action, but you should also check out the MDN page on the Array object, namely the sidebar where you'll see all the methods available.
When to Use the Filter Method
Sometimes you want to produce a new array with a subset of values from your original array. For this, the .filter() method is perfect:
const values = [1, 2, 3, 4, 5];
const filteredValues = values.filter((value) => value > 3);
console.log(filteredValues); // [ 4, 5 ]
To use .filter() you need to define a callback that will return a value that will evaluate (coerce to) true or false depending on whether you want to keep that element (true) or discard the element (false).
In the example, the callback is the arrow function that takes a single argument, value, and returns true if the value is greater than 3, and false otherwise. So you end up with a new array that contains only the values greater than 3.
Don't Forget the Return Keyword!
Remember if the function is on one line, as above, the return is implicit. If it is a multiline function, you need to return explicitly to .filter():
const filteredValues = values.filter((value) => {
return value > 3;
// ^^^^^^ required
});
If you end up getting a blank array back from .filter(), maybe you forgot to return. This is a common mistake, if you don't return anything then the function implicitly returns undefined, which is a falsy value, so .filter() will discard that element.
It Returns a Brand New Array
Also note that the .filter() operation does not mutate the original array, in true functional style. It returns a brand new array:
const values = [1, 2, 3, 4, 5];
const filteredValues = values.filter((value) => value > 3);
console.log(filteredValues); // [ 4, 5 ]
console.log(values); // [ 1, 2, 3, 4, 5 ]
This is true of many of the array methods. This makes them very useful for functional programming.
Arguments to the .filter() Callback
Like many array methods, the callback accepts more arguments than just the element in the array. With .filter() it calls the callback with the element, index, and original array.
const values = [1, 2, 3, 4, 5];
const filteredValues = values.filter((value, index, array) => {
console.log(value, index, array);
return value > 3;
});
// 1 0 [ 1, 2, 3, 4, 5 ]
// 2 1 [ 1, 2, 3, 4, 5 ]
// 3 2 [ 1, 2, 3, 4, 5 ]
// 4 3 [ 1, 2, 3, 4, 5 ]
// 5 4 [ 1, 2, 3, 4, 5 ]
console.log(filteredValues); // [ 4, 5 ]
Some Examples of Using .filter()
-
Removing Duplicates: If you need to filter out duplicate values from an array, you can use the index and the array itself to check if the current value is the first occurrence of that value in the array.
const uniqueValues = values.filter( (value, index, array) => array.indexOf(value) === index );Note: This is not the most efficient way to remove duplicates from an array. You can convert an array into a Set object to remove duplicates from an array quickly and efficiently, and then convert the set back into an array:
Array.from(new Set(values)) -
Filtering Based on Adjacent Elements: Sometimes you may want to remove consecutive elements in an array:
const noConsecutiveDuplicates = values.filter( (value, index, array) => index === 0 || value !== array[index - 1] ); -
Conditional Filtering Based on Array Properties: You might want to filter elements based on their position relative to the middle of the array.
const filterHalf = values.filter( (value, index, array) => index < array.length / 2 );This filters out items that are in the first half of the array.
Learn by Doing
Copy the examples from this lesson and get them working in your labs. Make a few variations, too.
If you're doing this course step-by-step, and especially if you're in the mentorship program, please be sure to push your work to GitHub when you're done.
Summary: JS Array Method - Filter
In this lesson, you:
- Learned to use the
.filter()method to create a new array populated with elements that pass a certain criteria provided by a given function. - Remembered the importance of the
returnkeyword in the callback function for.filter()in multi-line functions. - Recognized that
.filter()does not modify the original array but instead returns a new array, which aligns well with the principles of functional programming. - Saw that the
.filter()callback get's called with three arguments: the current element, its index, and the original array. - Reviewed a few practical examples, such as removing duplicates from an array and filtering based on array length or element position.