Learning Javascript Fundamentals: Filter.

Share on facebook
Share on google
Share on twitter
Share on linkedin
Using this filter function can help you receive specific data with specific arguments.

Imagine you’re coding a website, and you have a big list with data. That data has to be filtered specifically with parameters. We can use the Filter feature in JavaScript.

This article will show you the fundamentals of this Javascript feature to give you a basic understanding of filtering lists.


Initialize your project.

The first thing we need to do is having an environment set up. We use a simple HTML page and a javascript file:

<!DOCTYPE html>
<html>
<head>
<title>Lists</title>
</head>
<body>
<div class="container">
<h1>MY List</h1>
<div class="list">
    </div>
</div>
</body>
</html>

As you can see, there’s nothing inside the list. As we add more javascript, you can fill the list. First, create a main.js file and embed it into your HTML file:

<!DOCTYPE html>
<html>
<head>
<title>Lists</title>
</head>
<body>
<div class="container">
<h1>MY List</h1>
<div class="list">
    </div>
</div>
<script src="./main.js"></script>
</body>
</html>

Creating Our Data.

Let’s create some random data that we will use to filter:

const peopleArray = [
{
'name': 'Donald Trump',
'role': 'Former President',
'sex': 'Male',
'age': 74
},
{
'name': 'Elon Musk',
'role': 'CEO',
'sex': 'Male',
'age': 49
},
{
'name': 'Paul McCartney',
'role': 'Musician',
'sex': 'Male',
'age': 78
}
]

We create a const array with 3 people in it. To show this data on our site, we create an addList() function, but first, we need actually to get the list from our HTML document:

const list = document.querySelector('.list')

To add the data, we create addList() :

const addList = (array, element) => {
array.forEach(item => {
const li = document.createElement('li')
li.textContent = item.name
element.appendChild(li)
});
}

Just invoke the function:

addList(peopleArray, list)

This will be our result:

Image by Author: Bryan Dijkhuizen

Filtering Our Data.

Now the exciting part: The filtering itself. We create a new array:

const filteredArray = peopleArray.filter(person => person.age > 50);

Now we only see the people who are older than 50 years:

Image by Author: Bryan Dijkhuizen

Filtering by Sex.

We can use other filters, such as filtering by sex. Therefore, let’s add some women.

{
'name': 'Elizabeth II',
'role': 'Queen',
'sex': 'Female',
'age': '94',
}

And now filter that we only see the women:

const filteredArray = peopleArray.filter(person => person.sex === 'Female');

This will show:

Image by Author: Bryan Dijkhuizen

Bottom Line.

As you can see, it’s a beneficial function if you want to find specific data with specific arguments. I hope you have learned a lot from it.

bryan@dijkhuizenmedia.com

bryan@dijkhuizenmedia.com

Leave a Replay

Sign up for our Newsletter

Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit