JavaScript Array filter()

The JavaScript Array filter() method takes an array and a callback function as arguments, and returns a new array with all elements that pass the test defined by the given callback function.

  • Internally, the filter() method iterates over each element of the original array and pass each element to the callback function. If the callback function returns true, the element in included into the new returned array.
  • The new array will be subset of the original array.
  • The filter() operation does not modify the original array.
  • Because the filter() method returns a new array, we can chain the filter result with other iterative methods such as sort() and map().

1. Array.prototype.filter() Example

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const result = digits.filter(d => d > 7);

console.log(result);   //Prints [8, 9]

In the above example, we have an array of integers from 0 to 9. We want to get all the integers that are greater than 7.

In the above filter() example, we have specified a predicate which are anonymous function and return only boolean result.

To make the example more clear, we can rewrite the above example without predicates and lambda expressions.

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const result = digits.filter(isGreaterThanSeven);

console.log(result);   //Prints [8, 9]

function isGreaterThanSeven(d) {
	if(d > 7)
		return true;
	else
		return false;
}

2. Callback function

Each invocation of callback function used in filter() operation accepts three arguments:

  • The element from the original array (Required)
  • The index of the element (Optional)
  • Reference to the original array which is being traversed (Optional)

Let’s rewrite the above example one more time to understand the filter() operation more clearly.

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const result = digits.filter(isGreaterThanSeven);

console.log("Filtered array is : " + result);   

function isGreaterThanSeven(d, i, arr) {

	console.log("The array inside callback function is : " + arr);

	if(d > 7) {
		console.log("Selected element value is : " + d);
		console.log("Selected element index is : " + i);
		return true;
	} else {
		return false;
	}
}

Program output.

The array inside callback function is : 0,1,2,3,4,5,6,7,8,9		//Printed 9 times (for each element from 0 to 8)
Selected element value is: 8
Selected element index is: 8

The array inside callback function is : 0,1,2,3,4,5,6,7,8,9
Selected element value is: 9
Selected element index is: 9

Filtered array is : [8,9]

3. JavaScript filter() Examples

3.1. Find all names starting with substring

In the given example, we are checking each string in the array and discarding it if it starts with “test”.

const names = ["alex", "brian", "testName", "charles", "testD"];

const validNames = names.filter(str => !str.toLowerCase().startsWith("test"));

console.log(validNames);   //Prints ["alex", "brian", "charles"]

3.2. Filtering an array of objects

Suppose we have an array of Employee objects and want to find all employees earning more than 5k USD.

const employees = [
					{id: 1, name: "alex", salary: 4000},
					{id: 2, name: "brian", salary: 5000},
					{id: 3, name: "charles", salary: 6000},
					{id: 4, name: "david", salary: 7000},
					{id: 5, name: "emily", salary: 2000}
				];

const selectedEmployees = employees.filter(e => e.salary > 5000);

console.log(selectedEmployees);   

Program output.

[
	{id: 3, name: "charles", salary: 6000},
	{id: 4, name: "david", salary: 7000}
]

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.