What is the best way to filter an array? I know there is a filter function, but I don’t know what I need to put between the curly brackets.

When I work with arrays, I often need to filter an array by a criteria and get a new array with only the matching element. When I started coding, I usually did this with code along these lines:

var data = ['A', 'B', 'C'];
var result = [];
for (var i = 0; i < data.length; i++) {
    if (data[i] === 'B') {
        result.push(data[i]);
    }
}

This does work perfectly fine. But it is pretty cumbersome to write and needs a lot of lines. On top of this, it also buries the intent of what I want to reach with my code, especially if you have multiple steps where you need to filter your array.

A simple array filter function

So the next step could be to extract the common part of the filtering task. Every time I want to filter, I will need to loop over an array. The only thing which will differ each time is my condition when I want to select and add it to the result array. So this leads me to the following code:

function filter(input, condition) {
    var result = [];
    for (var i = 0; i < input.length; i++) {
        if (condition(input[i])) {
            result.push(input[i]);
        }
    }
    return result;
}

How to call it

I will show you four different ways how you can use your filter function in your code. Each of these variants is the same. But each one means you need to write a little bit less code. I prefer to you the last example when I write real code. But it is sometimes difficult to parse when you are not used to this syntax. And especially when you are a beginner, it can look like magic.

Variant one

var data = ['A', 'B', 'C'];

function check(item) {
    return item === 'B';
}
var resultA = filter(data, check); // resultA is now ["B"]

So in our example A, we define a regular JavaScript function called check which takes one argument (called item). This function will need to return a boolean result. In JavaScript, functions are first-level members. This means you can use the function names like a variable, and when we call the filter function, we can now provide our condition function as the second argument. Note that we don’t call the condition function at this point as it does not have any brackets there (its check and not check()) – this is important to keep in mind and a common source for errors. Our check function is now called within the for loop inside the filter function for each element in the data array.

Variant two

But with, by defining a special check function (which in most cases is only used once), we still need to write a lot of code. If we have a simple condition we check (like here, which only takes up a single line), we can simplify this further:

var resultB = filter(data, function(item) { return item === 'B'; });

Instead of defining the function before we call filter, we now directly define it in the place of the second argument. Also, note that this time the function does not have a name. The opening brackets now follow the function keyword. What you see here is called an anonymous function. It looks a lot better now. And most importantly, we don’t need to think of a good name for our one-off check. But we can do one better still.

Variant three

Let’s introduce the arrow function:

var resultC = filter(data, (item) => { return item === 'B' });

We don’t need the function keyword at all. Instead, we can use the arrow operator (=>).

Variant four

And when we write simple one-statement arrow functions, we also can drop the brackets (regular1 and curly) and the return statement from our code. Giving us our final version:

var resultD = filter(data, item => item === 'B');

You don’t need to reinvent the wheel!

And the best part is that you don’t need to write your filter function. JavaScript arrays already come with such a function. So, in reality, you would write it like this:

var result = data.filter(item => item === 'B');

It works as shown above in my implementation, it is not a complicated piece of code, but it is handy to know & understand how it works. You can read more about the JavaScript implementation here: Array.prototype.filter().

Before you go

I hope this post provided you with a new perspective on how you can write readable code. And the next time you need to filter an array, you can use the filter method instead of writing a plain for loop. And save some time on top as well. I would appreciate it if you signed up for my email list never to miss another post.


  1. Ok, I’m a bit thorn here. I find that dropping the regular brackets makes the parameter list a lot harder to scan. But when the function you call only takes a single parameter, it looks much nicer.
    Another point to remember is that it only works when your arrow function takes a single argument.
    Depending on my mood, I usually decide if I drop the round brackets. ↩︎