JavaScript/TypeScript Array Filter

Abdullah Mansoor
3 min readJan 24, 2022

In this article I’m gonna show you how to filter an array based on a search criteria.

So back to our above numbers array let’s say we want to return only the positive numbers. So we can use the filter method like below;

For the filter method, once again we need to pass a callback function; this function has 3 parameters;

  1. Value
  2. Index
  3. Array

Ref: Array Filter

So, out of this we only care about value, we don’t care about the index because I just want to see if the number or the value is positive. So to do this we can pass the value to the callback function, and we can write a simple expression like below;

In the above example we only return the value if it is greater than or equal to zero. So when we call the filter method, the above method will loop through the numbers array, and execute the callback function for each number for each element. Now if the element matches this criteria it will add this element to a new array and finally it will return a new array. Finally we can get the filtered array like below,

So if we console the filtered array we have only one, two and three. Since the above method has only one line of code and If you’re more familiar with arrow functions we can simplify the method like below;

In real world application you would be using an array of objects. For example see the google’s screenshot.

In this example search, if we click on the images tab, this also an example of filter. Google will search the results and it will filter the results that have the type as image.

Drop me a ‘Hi’ on:
WhatsApp: +94719994818
Facebook:
iAbu94
Email:
iabu94.dev@gmail.com

Follow me on:
LinkedIn: iabu94
Twitter:
iabu94
GitHub:
iabu94

--

--