What it is for

One of the global object types in JavaScript is the Array class. Unlike simple variables, arrays can store many different values in a list, where each entry has a specific index, which, in turn, can be used to refer to it in other functions. Users can interact separately with each array, and with all data at once, through the methods contained in the global Array class, one of which is the Array.filter() method.

This method allows you to retrieve data from an array selected by the same condition. Users can set it directly in the method, or through a link to a custom function. The Array.filter() method always reads the entire target array, and returns only the data with the true result. All relevant data will be returned as a new array, while the original array will stay unchanged.

Syntax

The Array.filter() method syntax implies that it must refer to an array, whose content will be checked against the condition specified in parentheses.

arrayName.filter(condition);

If condition is set through a function, then instead of "condition" there must be a reference to this function. Also, in this case this method can take an additional argument, which altogether will have the next form:

arrayName.filter(functionName, conObject);

conObject is an object which can be used to specify additional filtering context, such as data or a collection of data. Inside a function, it can be referenced by this, which allows us to use it as an additional condition inside an algorithm.

Also, in addition to conObject, you can pass parameters to functionName. In Array.filter(), this function can take:

  • element - the current element processed by the method.

  • index - the index of the current element in the processed array.

  • array - the one currently being processed.

The index, array and conObject arguments are optional, so they can be unspecified unless you use them in your script. The Array.filter() method syntax with all possible parameters, looks like this:

arrayName.filter(functionName(element, index, array) { ... }, conObject);

You can also use "arrow functions" in Array.filter(), which change syntax to:

arrayName.filter(element  => condition);

Tip. Arrow functions are functions defined using a special mark (=>). They are compact, but limited in functionality compared to full-fledged functions.

How to use Array.filter()

Let's consider options for setting conditions for the Array.filter(). Depending on the complexity of the condition for filtering, we can use 3 options for specifying them, which will return the same result.

But first we will create an array of numbers with 6 different digit values, which we will use for our tests.

let numbersArr = [86, 50, 88, 91, 96, 18];

Option 1

Let's create a filterNumbers function, in the conditions of which we will write number <= 70, where number will denote the value obtained from the numbers array. We will output the filtered values to the console, so we will place the entire construction into the console.log() method.

function filterNumbers(number) {
 return number <= 70;
}
const filteredNumArr = numbersArr.filter(filterNumbers);
console.log(filteredNumArr); // Output: [ 50, 18 ]

Option 2

JavaScript provides the ability to repeat our actions without creating a separate filtering callback function.

console.log(
 numbers.filter(function (number) {
   return number <= 70;
 })
);

Here we create a filter function and condition, in parentheses of the Array.filter() method, which allows us to make our code more concise. In this case, the result of executing this line will be equivalent to the previous option.

Option 3

Also in JavaScript there are arrow functions, the distinguishing feature of which is the assignment with the special => mark. They have certain limitations compared to regular functions, but can be written much shorter. In our case, filtering with arrow functions will look like this:

console.log(numbers.filter((number) => number <= 70));

To implement actions identical to those described in the previous two options, we declare a variable (number), designate an arrow function and set a filtering condition.

But JavaScript also has multilevel arrays, where several types of data can be stored under one record (index). For example, here is array friendsArr containing three entries, each with 2 string values:

let friendsArr = [
 { firstName: "Don", secondName: "Cooper" },
 { firstName: "Ted", secondName: "Talker" },
 { firstName: "Ben", secondName: "Barrel" },
];

In this case, the filtering will look like this:

function filterFriends(friend) {
 return friend.secondName === "Talker";
}
const filteredFriends = friendsArr.filter(filterFriends);
console.log(filteredFriends);

or

console.log(
 friendsArr.filter(function (arr) {
   return arr.secondName == "Talker";
 })
);

or

console.log(friendsArr.filter((arr) => arr.secondName === "Talker"));
// Output: 
//[
//  { firstName: 'Ted', secondName: 'Talker' },
//  { firstName: 'Ben', secondName: 'Talker' }
//]

Test yourself

  • Task 1. Conditions setting.

From this array of numbers, print to the console numbers: greater than 60, less than 70 and equal to 38. For each number, use a different version of the writing condition for the Array.filter() method.

let numbers = [26, 87, 79, 38, 99, 2, 23, 35, 79, 15];

Solution
First, let's declare an array of numbers, elements of which we will sort. Then, to apply the option 1 of the Array.filter() method mentioned above, we create a filterNum() that will check incoming numbers for the condition "if number > 60", where number are numbers from the array. In the next line, we will configure the output of the filter results to the console using the filterNum()

Then we apply option 2 for the filter condition number <70. And in the last line we implement option 3 - an arrow function with the filtering condition number equal 38.

function filterNum(number) {
 return number > 60;
}

console.log(numbers.filter(filterNum));
console.log(
 numbers.filter(function (number) {
   return number < 70;
 })
);

console.log(numbers.filter((number) => number === 38));

Result

After executing the code, the console should display three arrays with numbers that meet the specified conditions. Expected values in arrays:

[ 87, 79, 99, 79 ]
[ 26, 38, 2, 23, 35, 15 ]
[ 38 ]
  • Task 2. Using Array.filter() in multidimensional arrays. 

The multidimensional familyData array contains information about households: city, surname, family size. Using the Array.filter() method, print the following data to the console:

  • Families from Denver

  • Families with 3 or more people

  • Families with people who have the Talker last name.

let familyData = [
 { city: "New York", family: "Smith", size: "5" },
 { city: "Denver", family: "Gray", size: "2" },
 { city: "Mayami", family: "Talker", size: "1" },
 { city: "Denver", family: "Petrucci", size: "3" },
 { city: "Denver", family: "Talker", size: "3" },
 { city: "San-Francisco", family: "Smith", size: "4" },
 { city: "Mayami", family: "Ducker", size: "5" },
 { city: "Phoenix", family: "Williams", size: "3" },
];

Solution

To solve this, we will use the ability to access individual variables of the rows from the multidimensional array. First, we create the cityFunc() function that will return "success" if the accepted value (data) has the city value equal to "Denver". 

Then we will create the similar functions for the other two tasks, where size and family values will be checked, respectively. 

We implement the launch of all three functions through separate calls to the console.log() method in order to immediately output the result of their execution. For convenient reading of results, we can also add lines that will describe the results of execution.

let familyData = [
 { city: "New York", family: "Smith", size: "5" },
 { city: "Denver", family: "Gray", size: "2" },
 { city: "Mayami", family: "Talker", size: "1" },
 { city: "Denver", family: "Petrucci", size: "3" },
 { city: "Denver", family: "Talker", size: "3" },
 { city: "San-Francisco", family: "Smith", size: "4" },
 { city: "Mayami", family: "Ducker", size: "5" },
 { city: "Phoenix", family: "Williams", size: "3" },
];
function cityFunc(data) {
 return data.city === "Denver";
}
function familyNum(data) {
 return data.size > 4;
}
function familySurname(data) {
 return data.family === "Talker";
}

const cityArr = familyData.filter(cityFunc);
const familyNumArr = familyData.filter(familyNum);
const surnameArr = familyData.filter(familySurname);

console.log("Families from Denver: ");
console.log(cityArr);
console.log("Families consisting of more than 4:");
console.log(familyNumArr);
console.log("Talker's families:");
console.log(surnameArr);

Result

With correct conditions for Array.filter() we have to receive the next text:

Families from Denver:

[
  { city: 'Denver', family: 'Gray', size: '2' },
  { city: 'Denver', family: 'Petrucci', size: '3' },
  { city: 'Denver', family: 'Talker', size: '3' }
]

Families consisting of more than 4:

[
  { city: 'New York', family: 'Smith', size: '5' },
  { city: 'Mayami', family: 'Ducker', size: '5' }
]

Talker's families:

[
  { city: 'Mayami', family: 'Talker', size: '1' },
  { city: 'Denver', family: 'Talker', size: '3' }
]