DEV Community

Cover image for Using filter() in Javascript
Guilherme Toti
Guilherme Toti

Posted on

Using filter() in Javascript

Hey guys, what’s up?!

Today I want to teach you guys how to easily filter Arrays using the Array.prototype.filter method.

The filter() method it’s very simple to implement but it’s also very powerful and helpful way to filter your data.

In this article, I’ll use the same example data object that I used on my previous article, about the map() method:

So, the example data object is:

const data = [
    id: 1,
    name: 'John Doe',
    location: {
      city: 'São Paulo',
      state: 'SP',
      country: 'Brazil',
      zipcode: '00000-000'
    id: 2,
    name: 'Don Juan',
    location: {
      city: 'Rio de Janeiro',
      state: 'RJ',
      country: 'Brazil',
      zipcode: '11111-111'
    id: 3,
    name: 'The Rock',
    location: {
      city: 'Curitiba',
      state: 'SP',
      country: 'Brazil',
      zipcode: '22222-222'

Let’s imagine that you want to get from this array, only the objects where the location.state are equal to SP.

let newData = [];
for (let index in data) {
  const currentElement = data[index];
  if (currentElement.location.state === 'SP') {

It would work, right? Right! But, we are creating another variable to handle the new data and looping through the data object, searching for a state equal to SP and then, pushing this object to the new variable.

I think we can do better than this, can't we?
Yes, we can!

Yes! We can do it better! Using the filter() method!

Let’s see how it would be written using the filter() method:

const newData = data.filter(function(currentElement) {
  return currentElement.location.state === 'SP';

The basic idea of the filter() method is:

- Pass to the filter() method a function who:
  - Receives the current element of the data array you're filtering;
  - Do your logic;
  - Returns a boolean;
- The filter() method will loop through the data array executing your function and passing each element of the array as a param;
- If your function has returned true, then the current element will be added to the new array;
- Otherwise it will be just ignored;
- Returns the new array with the filtered data;

And if you are learning about ES6, the same code could be written as:

const newData = data.filter((currentElement) => currentElement.location.state === 'SP');

Cool, huh? :D

Probably at this moment you must be thinking about your old codes and how to refactor them to use the filter() method, right?

Well, I hope so!

That's all folks!
I hope you guys enjoy it, and keep learning!

Discussion (0)