Javascript Array.filter()

Basics

The filter() is a method of Array class. It creates a new array with all elements that pass the test implemented by the provided function.

Array.filter Example

In example below, we have an array of cities. Then we use filter() method to get a new array that contains only those city names that are more than 6 letters long.

ArrayFilter.js
var cities = ["London", "New York", "Tokyo", "Shanghai", "Melbourne"];

const result = cities.filter(city => city.length > 6);
        
console.log(result);

Code Explanation

In line 1, we define an array of cities. This is the original array and it will not change.

In line 3, we define a new variable called “result” that will hold the new array. The filter() method will iterate through the cities array and check the city names one by one if they are longer than 6 letters. If they are longer than 6 letter, they will be added to result array, otherwise they will be left out. City is a parameter that is given to filter() method.

In line 5, we print the result to console. It should result ["New York", "Shanghai", "Melbourne"].