Subscribe

JavaScript filter() method

āœļø

JavaScript filter method, how it works and why you need it

20 Nov, 2020 Ā· 2 min read

I figured Iā€™ve never really done an explanation of the Array methods in JavaScript. These are methods to make our lives way easier.

To explain how you must understand before these methods existed, we would have to make a manual loop and create a filter.

Using the Javascript filter() method

Letā€™s make a list of items with prices.

const items = [
  { name: 'T-shirt plain', price: 9 },
  { name: 'T-shirt print', price: 20 },
  { name: 'Jeans', price: 30 },
  { name: 'Cap', price: 5 },
];

Letā€™s say we want to filter out all the items over 10$.

const filter = items.filter((item) => item.price > 10);
// [ { name: 'T-shirt print', price: 20 }, { name: 'Jeans', price: 30 } ]

How this syntax works:

const new = original.filter(function);

Where new will be our new-to-use array, the original is the source, and we pass the function we want to apply.

So how did it look before?

Something like this.

const output = [];
for (let i = 0; i < items.length; i++) {
  if (items[i].price > 10) output.push(items[i]);
}
// [ { name: 'T-shirt print', price: 20 }, { name: 'Jeans', price: 30 } ]

It also works fine, but the array method makes it much quicker, especially with more advanced filters.

Thank you for reading, and letā€™s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next šŸ“–

Removing all vowels with JavaScript

3 Dec, 2022 Ā· 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 Ā· 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter