JavaScript Filter

Back to home
Logicmojo - Updated Aug 28, 2021



Javascript Filter

In JavaScript, the Array.filter() method is the most significant and extensively used technique for iterating over an array.

The filter function is called on an array and accepts one parameter: a callback, similar to map. It applies this callback function to each element in the array, and if the callback returns true, it adds the element to a new array. You would believe that using map, you can easily recreate this feature, but the main distinction is that map always produces an array of the same length as the original. (Well, almost usually, but that's a little more complicated and, to begin with, not in the spirit of map.) Filter, on the other hand, creates an array that is only as big as the amount of elements that pass through the callback.

The filter() method returns a new array containing all elements that pass the supplied function's criteria.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// function to check even numbers
function checkEven(number) {
  if (number % 2 == 0)
    return true;
  else
    return false;
}

// create a new array by filter even numbers from the numbers array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);

// Output: [ 2, 4, 6, 8, 10 ]



Syntax: arr.filter(callback(element), thisArg)

Parameters

Callback: The test function to run on each element of the array; returns true if the element passes the test, false otherwise.

Element: The element that is being passed from the array.

thisArg: The value to use as this when executing callback. By default, it is undefined.

💡 Filter function does not alter the original array and return a new array with only elements that are passed

Filter an Array of Objects

Suppose we have array that contains the names of students in a school:

var students = [
	{
		id: 1,
		name: "Alex",
		class: "First Grade",
		age: 5
	},
{
		id: 2,
		name: "Bill",
		class: "First Grade",
		age: 5
	},
{
		id: 3,
		name: "Connor",
		class: "Second Grade",
		age: 6
	}
];



What if we only want the pupils in first grade to be retrieved? This task is made simple with the help of Filter(). Let's construct a function that returns all first-graders from the array "students":

var firstGradeStudents = students.filter(function (student) {
	return student.class === “First Grade”;
});



Another real life example of filter function is in seaching. Let's take an example of an array for searching a particular element in it.

const languages = ["JavaScript", "Python", "Ruby", "C", "C++", "Swift", "PHP", "Java"];

function searchFor(arr, query) {
    function condition(element) {
        return element.toLowerCase().indexOf(query.toLowerCase()) !== -1;
    }
    return arr.filter(condition);
}

let newArr = searchFor(languages, "ja");
console.log(newArr); // [ 'JavaScript', 'Java' ]

// using arrow function
const searchArr = (arr, query) => arr.filter(element => element.toLowerCase().indexOf(query.toLowerCase()) !== -1);

let newLanguages = searchArr(languages, "p");
console.log(newLanguages); // [ 'JavaScript', 'Python', 'PHP' ]



Conclusion: At this point, you should have a better understanding of JavaScript Filter. How the filter function is used in production, and how it can help make code more readable and versatile.