DEV Community

Cover image for Filter Array Method
Amrasakpare Lawrence
Amrasakpare Lawrence

Posted on • Updated on

Filter Array Method

Hey there guys 😀, We’ll be talking about filter() method in this article. I will explain exactly what this method does and how you can use it. So let’s dive right in 😉

🗃️ What is filter() method?

The filter()method 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. Basically what this means is that the filter() method filters out the only elements that meet the conditions in a function. Let’s see an example 👇🏾

const fruits = ['Apple', 'Banana', 'grape', 'mango', 'orange'];

const filterFruit = fruits.filter((fruit) => fruit === 'grape');

console.log(filterFruit); //output: grape
Enter fullscreen mode Exit fullscreen mode

In this example above, we created an array of fruits and used the filter() to filter out everything that isn’t grape and keep just the grape. Let’s explain the second line of the code for more clarity. What the second line of code means is that: given an array called fruits, take each element in the array and check if it exactly matches the string grape. If it doesn’t discard it, and if it does add it to a new array (which in this case is called*filterFruit* ).

Let’s take one more example 👇🏾

const gadgets = [
  { name: 'Iphone', price: 3000, location: 'Delta' },

  { name: 'Samsung Galaxy', price: 10000, location: 'Lagos' },

  { name: 'Iphone', price: 1000, location: 'Delta' },

  { name: 'Iphone', price: 2000, location: 'Lagos' },

  { name: 'Infinix', price: 4000, location: 'Delta' },

  { name: 'Samsung Galaxy', price: 3000, location: 'Delta' },

  { name: 'Sony', price: 500, location: 'Ibandan' },
];

const gadgetName = gadgets.filter((gadget) => gadget.price < 3000);

console.log(gadgetName);

//output
// {name: 'Iphone', price: 1000, location: 'Delta'}
// {name: 'Iphone', price: 2000, location: 'Lagos'}
// {name: 'Sony', price: 500, location: 'Ibandan'}
Enter fullscreen mode Exit fullscreen mode

In this second example above, we created an array of objects(gadgets) and we used the filter() to filter out the price of the gadgets that is less than 3000

🏗️ How does filter() work?

In the example above we have an array of gadgets. All JS arrays have a set of built-in methods that we can use. filter() is one of those, and we can access it with the syntax Array.filter().

Filter is a higher-order array function, which means that we can pass another function for it to do something with. It takes three parameters like the forEach() But we will only focus on the first parameter which is a function that is called once for each item in the array and will test each element in the array to decide if they’re being kept or discarded.

Using the example above, filter will then pick up each individual element of the array and examine it against the test we provided. The current element that filter is looked at is provided to us as the first argument. That’s the first gadget we see. It is a variable that we can name whatever we want. But it’s logical that an array of gadgets a single element is one which is gadget.

After the arrow function, we use the gadget variable to implement the test we want. And filterdoes the rest. It will iterate through the whole array and return an array of everything that matches our test.

💼 Use Cases of filter()

There are multiple ways of applying the filter() method but we’ll be talking about 3 use cases.

🔍 Searching in array

You can use the filter() to filter array content based on search criteria. Here is an example 👇🏾

const games = [
  'witcher',
  'Grand theft auto',
  'uncharted',
  'mario',
  'god of war',
];

const filterItems = (game, search) => {
  return game.filter((letter) => letter.includes(search.toLowerCase()));
};

console.log(filterItems(games, 'ar')); // output ['uncharted', 'mario', 'god of war']
console.log(filterItems(games, 'an')); // output ['Grand theft auto']
Enter fullscreen mode Exit fullscreen mode

🤏🏽 Filtering out small or big values

The filter() method can be used to create a filtered array of elements with small or big values. Here is an example 👇🏾

const numbers = [100, 20, 9, 6, 12, 30];

const filterValue = (value) => {
  return value >= 20;
};

const filterSmallValues = numbers.filter(filterValue);

console.log(filterSmallValues); // [100, 20, 30]
Enter fullscreen mode Exit fullscreen mode

3️⃣ Filtering odd numbers

The filter() method can be used to filter out odd numbers in array . Here is an example 👇🏾

const numbers = [1, 3, 7, 4, 5, 8, 10, 11, 12, 13, 14, 15];

const isOdd = (value) => {
  return value % 2 === 1; // Check if the value is odd and return true or false
};

const filteredNumber = numbers.filter(isOdd);

console.log(filteredNumber); // [1, 3, 7, 5, 11, 13, 15]]
Enter fullscreen mode Exit fullscreen mode

If you like to see a real world example where this filter method is applied, Here is a link to small website I built and you can also get the source code from there too.

https://filterproducts.netlify.app/

That’s it guys 😀. I hope you learned something from this article. Always remember that the only way to get good at something is by applying what you have learnt as soon as possible. See you next week.

Top comments (5)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Might want to review your isOdd function... 🤔

Collapse
 
devlawrence profile image
Amrasakpare Lawrence

I have reviewed it and made the correction. Thanks Randy I appreciate 🙌

Collapse
 
jonrandy profile image
Jon Randy 🎖️

It can be further simplified by removing === 1 👍

Collapse
 
volodyslav profile image
Volodyslav

Nice article 😁 Your site is really cool. I wonder what you use on backend?🤔

Collapse
 
devlawrence profile image
Amrasakpare Lawrence

Thanks Vlad. I just coded the frontend. There is no backend code