Basics of Javascript · Array · filter() (method)
This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.
Hello dev newbs! Today is the day to cover one of the “big ones”. The filter() method is one of the three most important methods of the Array object. The others are map() and reduce() and we will cover them later. But for now, let’s kick it off in a big style with the filter() method.
The method filter() creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. The test function is usually written in an arrow format as we will see in the basic example.
// Example 1
// basic usage
console.log("EXAMPLE 1");
console.log("--------------------------------------------------");
let greetings = ["hello", "ola", "ciao", "hallo", "konichiwa", "ni hao", "namaste"];
// get only greetings shorter than 6 characters
console.log(greetings.filter((word) => word.length < 6));
// returns ['hello', 'ola', 'ciao', 'hallo']
let numbers = [11,164,785,325,4126,98,7,4,5,62,247];
// get only odd numbers - modulo result truthy
console.log(numbers.filter((number) => number % 2));
// returns [11, 785, 325, 7, 5, 247]
In the first example, I show you how to filter elements of the array based on the individual property of the elements itself — specifically based on the number of characters the string element contains. We only want elements with length less than 6 characters.
The second example uses clever feature of JavaScript. Any value is either truthy or falsy. When we use modulo to calculate the remainder after division, the resulting value greater than zero is always truthy and value equal to zero is falsy. So this shortened expression basically checks for all the numbers in an array that are even — or in other words — have non-zero remainder after division by number two.
The function used to test whether an element passes or not does not have to be just one-liner using arrow function syntax. We can also pass traditionally defined functions. Let’s see it with more advanced examples in the next block of code.
// Example 2
// advanced use
console.log("EXAMPLE 2");
console.log("--------------------------------------------------");
let randomContentArray = [150, -1, true, {id: 147}, 2.14457, null,, 'hello', 17, 0, 4578];
function onlyPositiveNumber(item){
if(Number.isFinite(item) && item > 0){
return true;
}
return false;
}
// return only numbers which are positive
console.log(randomContentArray.filter(onlyPositiveNumber));
// returns [150, 2.14457, 17, 4578]
greetings = ["hello", "ola", "ciao", "hallo", "konichiwa", "ni hao", "namaste"];
// check if element contains certain query
function filterItems(array, query) {
return array.filter((el) => el.includes(query));
}
// return greetings containing “ho”
console.log(filterItems(greetings , "ha"));
// returns ['hallo', 'ni hao']
// return greetings containing “ho”
console.log(filterItems(greetings , "i"));
//returns ['ciao', 'konichiwa', 'ni hao']
The first use case deals with the situation when we need to filter out only numbers from an array that can possibly contain any value. We achieve it by creating a filtering method that checks the type of a value by calling a method from object Number called isFinite() which only returns true for numeric values. Second condition is that the value is greater than zero.
The resulting array contains only numbers with positive values.
The second part of this code block utilizes the filter method inside its body. Two arguments are used — array itself and a query which is used to check whether a given element contains it as a substring.
Sometimes, we need to use more than just the element itself when using the filter() method. What does it look like when we need to use both the element, index and array itself? Let’s see in the next example.
// Example 3
// using all callbackFn arguments
console.log("EXAMPLE 3");
console.log("--------------------------------------------------");
const people = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 22 },
{ name: 'David', age: 18 },
{ name: 'Eva', age: 16 },
];
const olderThanPrevious = people.filter((person, index, array) => {
if (index == 0)
return person;
if (person.age > array[index-1].age)
return person;
});
// return people who are older than previous person in array
console.log(olderThanPrevious);
// returns following array:
// 0 : {name: 'John', age: 25}
// 1 : {name: 'Alice', age: 30}
// 2 : {name: 'Charlie', age: 22}
console.log([1, , undefined].filter((x) => x === undefined));
// returns [undefined]
console.log([1, , undefined].filter((x) => x !== undefined));
// returns [1]
We can use the filter method on arrays that contain more complex structures, like objects. In the first example, we will only pass the people who are older than the person who is in front of them in an array. We are leveraging both index and array arguments of the callback function.
The second example shows that the filter method skips over empty slots in the array. However, it will handle the undefined values.
Last exercise of the day will be behavior with array-like objects. Let’s see how they work with the filter() method…
// Example 4
// array-like object
console.log("EXAMPLE 4");
console.log("--------------------------------------------------");
const arrayLike = {
length: 3,
0: "a",
1: "e",
2: "c",
3: "d"
};
console.log(Array.prototype.filter.call(arrayLike, (el, idx, arr) => (el.charCodeAt(0) - idx) == 'a'.charCodeAt(0)));
// returns ['a', 'c']
The last example shows how array-like objects behave similarly like actual arrays. In this case, we wanted to return only characters that are positioned on the index where they belong when sorted alphabetically. As we can see both “a” and “c” are in the correct position, but that does not apply to “e” which should be at position 4. But since the length of the object is set to value 3, only numerical properties with index less than 3 will be taken into consideration.
Thank you for sticking with me till the end of this lesson. This was method filter() and its various use cases. I am sure you can find many others and I will be happy if you share them with me in the comments. As usual, see you in the next video.