How to Filter Arrays in JavaScript, With Examples

Javascript: filter arrays

We’ve covered arrays in JavaScript pretty extensively on LinuxScrew. This article will show you how to use the filter method – with easy-to-follow examples.

JavaScript Arrays

Arrays are a type of variable that holds a list of other values or variables. They’re one of the fundamentals of computer programming.

These lists contain items at positions (called indexes). These items can be anything – numbers, strings, complex objects – whatever you want to store.

Arrays are super useful. You might use them to store the rows in a table for calculations, or you might use them to hold references to all of the bad guys in your video game so you can quickly find them and update their status in the game.

Filtering Arrays

In the context of JavaScript arrays, filtering means taking the original array, removing items in the array that don’t match the given criteria – and returning a copy of the original array with those items removed.

For example, you might have an array of bad guys in your game – some bad guys are red, some bad guys are blue. You can write a filter to get a new array containing only the blue bad guys.

The JavaScript Array filter() Method

The filter() method available on arrays provides a convenient way to do this filtering. You can provide it with any criteria, and it will return an array containing only the items matching those criteria.

array.filter(item => filter_function);

Note that:

  • array can be any array variable
  • item is the variable name that will be assigned to each item in the array inside the filter_function
  • filter_function is a function or statement which should return a boolean (TRUE or FALSE) value

The filter function needs only to return a TRUE or FALSE boolean value (manually or as a result of using a comparator) – if the value is not TRUE, the item will be removed from the resulting array.

Examples

Here it is in action:

var furniture = ['chair', 'bed', 'couch', 'table'];
var startsWithC = furniture.filter(item => item[0]  == 'c'); // [ "chair", "couch" ]

Above, we define an array of furniture items.

Then, we create a new array containing filtered values from the first array, in this case checking that the first character in the name of the furniture item is the letter ‘c.’

This is done with arrow function expressions – a short way of writing a single line function. Each item in the array is given the variable name item, and the one-line function which will be used to filter is placed after the arrow (=>).

It is possible to write more complex filters with multiple criteria by using a longer form of the arrow function expression, where a more complex expression is returned from code wrapped in curly braces ({}):

var furniture = ['chair', 'bed', 'couch', 'table'];
var filteredItems = furniture.filter(item => {
    console.log('Checking item: ' + item)
    if (item[0]  == 'c'){
        return true;
    } else if(item.length < 4){
        return true;
    }
    else {
        return false;
    }
}); // [ "chair", "bed", "couch" ]

Above, several actions are taken in the filter function. The item is printed to the console, and it is then checked against two conditions – whether it starts with a c or has less than 3 letters.

Check out these other useful things you can do with JavaScript arrays:

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *