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 ... [Read Full]
markdown guide
 

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!

 

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!

 

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.

 

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.

 

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

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

 

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

 

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.

 
code of conduct - report abuse