DEV Community

Cover image for JavaScript filter() method
Chris Bongers
Chris Bongers

Posted on • Edited on • Originally published at daily-dev-tips.com

13 2

JavaScript filter() method

I figured I've never really done an explanation on Array method 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 in there.

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 }
];
Enter fullscreen mode Exit fullscreen mode

Now 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 } ]
Enter fullscreen mode Exit fullscreen mode

How this syntax works:

const new = original.filter(function);
Enter fullscreen mode Exit fullscreen mode

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

So how it looked before?

Something like this.

let output = [];
for(var 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 } ]
Enter fullscreen mode Exit fullscreen mode

Also works fine, but especially when it comes to more advanced filters the array method makes it so much quicker.

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

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

DEV works best when you're signed in—unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay