Filtering an array of objects in JS

John Thomas
JS tidbits
Published in
1 min readMay 5, 2020

Problem statement:

Given a list of flowers, we need to filter out only the flowers that are red in color.

Below is our list of flowers.

Solution:

You might get to coding right away. And your first instinct could be to write a for loop. And it could come out something like the below snippet.

But, there is a shorter way to do it. In Javascript, array objects have a filter method out of the box. It is a higher order function and takes another function as parameter

The isRedFlower function takes a flower object and returns true if the flower is red and false otherwise. And this isRedFlower function is passed as argument to the filter function.

We can make this code reusable by creating a function which takes two parameters — the array of objects, the function which accepts or rejects the object in picture.

And that was the filter function in action!

Thanks for reading :)

--

--