JavaScript Array filter() Method

 The filter() method is another built-in array method in JavaScript that allows you to create a new array containing all elements that pass a certain condition.

It doesn’t modify the original array  instead, it returns a new array with the elements that satisfy the provided condition.

The basic syntax of the filter method:

				
					const newArray = orignalarray.filter(function(element, index, array) {
  // return true to keep the element in the new array, false to exclude it
});

				
			
  • element: The current element being processed in the array.
  • index: The index of the current element within the array.
  • array: The array that filter is being applied to.

Let’s see an Example how use filter() method.

Suppose you have an array of objects that holds users’ detail like name, age and occupation. You can decide to filter for users whose age matches a specific condition.

				
					let users = [
    { name: 'John', age: 25, occupation: 'gardener' },
    { name: 'Lenny', age: 51, occupation: 'programmer' },
    { name: 'Andrew', age: 43, occupation: 'teacher' },
    { name: 'Peter', age: 81, occupation: 'teacher' },
    { name: 'Anna', age: 47, occupation: 'programmer' },
    { name: 'Albert', age: 76, occupation: 'programmer' },
]
				
			

Javascript Users Array

You can now filter the array of objects using the age to return a new array whose age is greater than 40 and whose occupation is equal to programmer

				
					let filteredUsers = [];
for (let i= 0; i<users.length; i++) {
    if (users[i].age > 40 && users[i].occupation === 'programmer' ) {
        filteredUsers = [...filteredUsers, users[i]];
    }
}
console.log(filteredUsers);
				
			

Iterate over an array using for loop

This will return an array of three users who meet the specified condition.

javascript filter method

Now, this works alright. But a better way to filter through an array is to use the ES6 filter() method.

				
					let filteredUsers = users.filter((user) => {
    return user.age > 40 && user.occupation === 'programmer';
});

console.log(filteredUsers);
				
			

This will return the exact output, but you’ll notice that your code is quite clean. It is also important to know that you can re-write the code above with one line by arrow function, and take away the return statement:

				
					let filteredUsers = users.filter(user => user.age > 40 && user.occupation === 'programmer');
console.log(filteredUsers);

				
			

Both code blocks will output the filtered users:

javascript filter method

The filter method makes it easy to perform more operations directly without creating as many variables because it is great at chaining with other functional methods.

 For more information about JavaScript:

click here for YouTube video

Leave a Reply

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