DEV Community

Filter Arrays with the Javascript Filter() Method

Sarah Chima on December 29, 2018

Filtering unwanted elements to reduce the size of an array is fun right? JavaScript array filter method makes it even more fun. In my last blog po...
Collapse
 
joelnet profile image
JavaScript Joel

I have fallen in love with this syntax over a for loop:

const isOlderThan18 = (age) => age > 18;

The reason being, with a for loop, the focus is on operating on the collection as a whole.

By making this minor change, we have simplified our work to just operating on a single item and not a whole collection of items, which is more complex.

Once we have solved how to handle the single item, it becomes easy to then apply that solution also to the collection.

const map = require('ramda/src/map')

const isOlderThan18 = (age) => age > 18;
const mapOlderThan18 = map(isOlderThan18)

const olderThan18 = mapOlderThan18(ages)

Cheers!

Collapse
 
stephencweiss profile image
Stephen Charles Weiss

Great post Sarah! Thanks for writing it and beautiful website too by the way :).

Off topic: When you write on Dev.to... which style are you using for your code snippets? I've been using gist (since it's what I do on my site), but yours is so much prettier!

Collapse
 
vier31 profile image
Jan Schröder • Edited

From what it looks like on my end, the code snippets are inside triple backticks in the markdown, which creates this kind of code snippet in the article. Plus the definition of the language after the initial three backticks.

Collapse
 
frontendengineer profile image
Let's Code

Hi Sarah, great post! Happen to record a video about js filter similar topic like you did here. Thanks for educating the community.

youtube.com/watch?v=hvUs_mQc_wo&li...

Collapse
 
budisalah profile image
Budi Salah 🐋 • Edited

Hello guys.
I need some help, please 😥

At the end of this post, @sarah_chima said

Remember the example mentioned at the beginning of this post? Can you try to use the filter method to achieve the same thing?

I tried to do it but I can't. I want the final output to be like this using filter method:

[4, 3, 36, 7]

Thanks, guys.

Collapse
 
vier31 profile image
Jan Schröder

You would need to put the if statement in the callback of the filter()

const oddSqrRoots = numbers.filter(num => num % 2 != 0)

Collapse
 
raiivis profile image
Raivis Vasiļevskis

Nicer synthax doesn't always mean better results. This way is slower than traditional for loop. Probably it does not matter for small arrays, but try to test it with large arrays. You will see quite a big difference in the speed

Collapse
 
joelnet profile image
JavaScript Joel

This statement is misleading. In reality there will be zero impact to performance within an application. Unless you are designing a game engine, this metric is worthless.

Collapse
 
teexee19 profile image
Tochukwu Franklin Ene

Awesome!! thanks Sarah.