After we have covered the JavaScript Array Find Method in the last article, allowing us to return one single element of an Object by searching for a string value, it is time to move forward and learn how to return multiple values from an Array by searching for a string or number using the JavaScript Array Filter Method.
As always, we are going to break the code down and go through it step-by-step, so you will be able to fully understand each of its components.
As always, there is a Repl.it that you can fork and play around with!
🔥 Learn JavaScript Programming – Beginner Friendly!
🔨 JavaScript Basics
👉 JavaScript alert()
👉 Difference between Let and Const
🔸 JavaScript Arrays
👉 JavaScript Array Filter
👉 JavaScript Array Find
👉 JavaScript forEach (Arrays)
👉 JavaScript Slice (Arrays)
👉 JavaScript Spread Operator
🔸 JavaScript Strings
👉 JavaScript Slice(Strings)
👉 JavaScript Includes
🌐 Web Development with JavaScript
👉 Store User Input in a variable with JS
⚙️ JavaScript Specifics
👉 Sorting Numbers in JS
👉 JavaScript Fetch API
👉 toLocaleDateString in JavaScript
Table of Contents
- What are we working with?
- The JavaScript Array Filter Method
- Creating a JavaScript Array Filter Function
- Conclusion
What are we working with?
In today’s example, we are going to use an array of objects consisting of car brands and models.
const cars = [
{
brand: "Audi",
model: "A4"
},
{
brand: "Audi",
model: "100"
},
{
brand: "BMW",
model: "318i"
},
{
brand: "BMW",
model: "i8"
},
{
brand: "Tesla",
model: "P100D"
}
]
Code language: JavaScript (javascript)
Our task? Pull out each model of a certain brand from this array of objects using the JavaScript Array Filter Method. Let’s get our hands dirty!
The JavaScript Array Filter Method
Let’s start to create the JavaScript Array Filter Method.
let findBrands = cars.filter(function(item) {
const carBrand = item.brand === "Audi";
return carBrand;
});
console.log(findBrands);
Code language: JavaScript (javascript)
This is the bare filter()
method. Let’s break it down.
let findBrands = cars.filter(function(item)
Code language: JavaScript (javascript)
We create the variable findBrands and make it equal to the cars.filter(function(item)). Cars stands for the name of our array, meaning we call the method on our cars array.
The filter()
method calls a callback function one time for every element in the array and then constructs a completely new array of all elements that returned a truthy value. Our item argument reflects those values, this is why we compare if our item.brand
is equal to our search string.
const carBrand = item.brand === "Audi"
Code language: JavaScript (javascript)
Now we create a variable called carBrand. As mentioned above, we use this variable to store the values that are true according to our comparison to item.brand and return them later on.
Finally, we console.log our find.Brands variable. The output is the following:
[ { brand: 'Audi', model: 'A4' },
{ brand: 'Audi', model: '100' } ]
Code language: Bash (bash)
If we would go ahead and change our search string from “Audi” to “BMW“:
let findBrands = cars.filter(function(item) {
const carBrand = item.brand === "BMW";
return carBrand;
});
console.log(findBrands)
Code language: JavaScript (javascript)
the output is the following:
[ { brand: 'BMW', model: '318i' },
{ brand: 'BMW', model: 'i8' } ]
Code language: Bash (bash)
Now keep in mind that the input of our search string is case-sensitive. If we would write “bmw” instead of “BMW“, the output would be:
[]
Code language: JSON / JSON with Comments (json)
To fix this, we can make use of the toLowerCase() method.
let findBrands = cars.filter(function(item) {
const carBrand = item.brand.toLowerCase() === "bmw";
return carBrand;
})
Code language: JavaScript (javascript)
This transforms all input to lowercase characters, getting rid of case sensitivity.
Creating a JavaScript Array Filter Function
To make this code a little bit more convenient for later use, let’s wrap everything in a function and refactor our code a bit, so we will be able to pass the array and our search strings as arguments instead of manipulating our filter() method each time.
const findBrand = function(array, brand) {
return array.filter(function(item) {
const carBrand = item.brand.toLowerCase() === brand.toLowerCase();
return carBrand;
});
};
console.log(findBrand(cars, "Audi"))
Code language: JavaScript (javascript)
What we did here was, we created a new function called findBrand with two arguments: an array and the brand we search for. Then we removed the let findBrands variable and replaced it with return array.filter(function(item)).
Next, we replaced our actual search string “bmw” with the brand argument of our findBrand() function. To still be able to do case-insensitive searches, we also need to transform the brand variable toLowerCase().
Finally, we console.log(findBrands(cars, “Audi”)); where cars are the name of our array and “Audi” is our search string. Now we are able to conveniently use this function to search for whatever we want. let’s give it a final test:
console.log(findBrand(cars, "tesla"))
Code language: JavaScript (javascript)
Note that “tesla” is written with lower case, whereas in the original array it is written with capitalized letters “Tesla“, the output nevertheless is:
[ { brand: 'Tesla', model: 'P100D' } ]
Code language: Bash (bash)
Conclusion
This JavaScript Array Filter method really is useful in so many different cases. Look up the MDN documentation for further details. Make sure to keep it in the back of your head, or bookmark this article for later reference. I hope I was able to break it down so you are able to fully understand how it works. Let me know in the comments below.