In the previous article, I talked about iterating over arrays using the map
array method. You can check it out below:
Understanding Javascript Array Series VI - Array Loops & Iteration Part III
Nedy Udombat ・ Oct 4 '19 ・ 4 min read
Today, I will talk about using Filter to iterate over arrays.
FILTER
From time to time, we would want to filter out things from an array that we do not need. Take a look at this example where we want to filter out all odd numbers from a certain array.
We could achieve this with a for ...
loop by doing this:
const numbersArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbersArray = [];
for (let i = 0; i < numbersArray.length; i += 1) {
if (numbersArray[i]%2 === 0) {
evenNumbersArray.push(numbersArray[i])
}
}
console.log(evenNumbersArray) // [2, 4, 6, 8, 10]
In this situation, we had to use a for ...
loop and an if
statement to achieve. We could achieve this same result by using the filter()
method.
const numbersArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbersArray = numbersArray.filter(number => number%2 === 0);
console.log(evenNumbersArray) // [2, 4, 6, 8, 10]
From the example, above we can see that the filter()
method doesn't mutate the original array instead it creates a new array and stores the elements of the previous array that pass the condition set.
The filter()
method creates a new array of elements that passed a specified condition from an original array. In the example above, the filter()
method created a new array with even number elements.
Let's take a look at its syntax:
// syntax
const newArray = arr.filter(([currentValue], [arrayIndex], [arr]) => {
// [specified condition]
});
or
const newArray = arr.filter(callback([currentValue], [arrayIndex], [arr]));
On the left side of the assignment, the result of the filter statement is stored in a new variable. It can be declared by using const or let.
[currentValue]: This is the current item in the array that is being processed. After the procession, the current value becomes the value of the next element in the array.
[arrayIndex]: This is the index of the current value in the array. This also changes after the current value has been processed.
[arr]: This is the array being iterated over.
[callback]: This is basically a function to be performed on each element of the array, if the function returns true then the element is added to the new array, else it is skipped. It accepts the first three items (currentValue, index, and array) as arguments. We can declare the callback function before using it like this:
const numbersArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 10];
const isEvenNumber = num => num%2 === 0
// using a callback function
const evenNumbersArray = numbersArray.filter(isEvenNumber);
console.log(evenNumbersArray) // [2, 4, 6, 8, 10]
Some examples of filter()
in action.
- Lets filter an array to get all Barcelona players
const players = [
{ name: "messi", club: "Barcelona"},
{ name: "Ronaldo", club: "Juventus"},
{ name: "Kante", club: "Chelsea"},
{ name: "De Jong", club: "Barcelona"},
{ name: "Semedo", club: "Barcelona"},
{ name: "Eriksen", club: "Totenham"},
{ name: "Pogba", club: "Man utd"},
{ name: "Alba", club: "Barcelona"},
{ name: "Dembele", club: "Barcelona"},
]
const barcaPlayers = players.filter(player => player.club === "Barcelona");
console.log(barcaPlayers);
//[
// { name: "messi", club: "Barcelona"},
// { name: "De Jong", club: "Barcelona"},
// { name: "Semedo", club: "Barcelona"},
// { name: "Alba", club: "Barcelona"},
// { name: "Dembele", club: "Barcelona"},
//]
Conclusion
Array.filter()
is great when you want to literally filter out things from an array. It doesn't mutate the original array.
QUICK QUIZ: Feeling up to it? try this it and drop your answers in the comment section.
// Return an array of only prime numbers from the given array
const numbersArray = [1, 2, 3, 4, 5, 6, 7, 8, 11, 15, 17, 23, 24, 25, 29, 30];
// Return an array of all words that begin with a vowel in the given array
const randomWords = ["Nedy", "Adesoji", "Akaniru", "Umbrella", "Barcelona", "Xylophone"];
Got any other instances for the use of the filter
function? Please do well to share it in the comment section.
That's all for today, tomorrow we will talk about another set of functions used in array Iteration.
Here is the link to the other articles on this Array series written by me:
- What is an Array?
- Alternate ways of Creating an Array.
- Array Properties
- Array Loops & Iteration Part I
- Array Loops & Iteration Part II
- Array Loops & Iteration Part III
Got any question, addition or correction? Please leave a comment.
Thank you for reading. 👍
Top comments (2)
// Return an array of all words that begin with a vowel in the given array
const randomWords = ["Nedy", "Adesoji", "Akaniru", "Umbrella", "Barcelona", "Xylophone"];
const startWithVowelWords = randomWords.filter((random_word) => {
const vowels = ["a", "e", "i", "o", "u"];
return vowels.includes(random_word.toLowerCase().substring(0,1))
});
Nice solution @pavilandoangelo 👍