Sunday, September 5, 2021

Master JavaScript Filter Function with 4 Examples

Must read

What is filter function in JavaScript?

The JavaScript filter function is one of the commonly used array operations in javascript. As the name suggests array filter in javascript is used to filter out elements in an array and return the remaining elements

Array filter is similar to array map function but filter applies the callback function passed to each element in the array and then decides if to keep or not to keep the element depending on our condition used in the filter is True or False.

How do you write a filter function in JavaScript?

Syntax

array.filter( 
    callback(element, index, self) {
        // your code logic
    }
, thisValue);

Javascript filter function parameters used

  • element (Optional)-> This is the current element which is being passed
  • index (Optional)-> This is the index of the current element which is being passed
  • self (Optional) -> This is the whole array itself.
  • thisValue (Optional) -> This is the context to be passed as this can be used while executing the callback function. Used in Example Three.

Example One: How do you filter an array?

var simpleArray = [11, 32, 41, 52, 56, 92, 70, 85];
var evenNumArray = simpleArray.filter(
   function (element) { 
   	return element % 2 === 0;
   }
);
console.log(evenNumArray)

The output will be:

[32, 52, 56, 92, 70]

Example Two: Using Javascript filter function to remove Duplicate elements in array

var usersArray = ['John', 'Amy', 'Bob', 'Alan', 'John', 'Amy'];

var uniqueArray = usersArray.filter(
   function (element, index, self) { 
   	return self.indexOf(element) === index;
   }
);

console.log(uniqueArray);

The Output will be:

["John", "Amy", "Bob", "Alan"]

Code Summary

  • The call-back function we pass in the above code checks the indexOf each element with IndexOf() function and compares it to the index value that the call-back function passes. if both the values are the same then only it returns back the element
  • Let’s take the first elementJohn” -> the indexOf() will return 0 and index variable will also return 0. Therefor the statement is true. “John” is returned back.
  • Let’s take the fifth element which is a duplicate value in array “John” -> the indexOf() will return 0 instead of 4 because the indexOf() function only gives the first position index of a value which is 0. Therefore the indexOf() value will be 0 and the index variable will be 4. Which will be a false statement and the fifth element “John” will not be returned.

Example Three: Filter array of objects JavaScript

In this example, we will be using thisValue parameter of the filter array function which will be used as a context of the limit of salary. The variable used for this is salaryLimit.

Using salary limit Javascript filter function will get salary greater than 5000 in array of objects.

let employees = [
	{ name: "John", salary: 5000 },
	{ name: "Bob", salary: 9000 },
	{ name: "Amy", salary: 20000},
	{ name: "Alan", salary: 10000 }
];

let salaryLimit = 6000;

let salary = employees.filter(
	function(elements) {
    	return elements.salary > salaryLimit; 
	},
   salaryLimit
);

console.log(salary);

The output will be:

[{
  name: "Bob",
  salary: 9000
}, {
  name: "Amy",
  salary: 20000
}, {
  name: "Alan",
  salary: 10000
}]

Example Four: Javascript filter function on multiple conditions

We can also use the javascript filter function on multiple conditions. Let’s take the example above and try to filter using the salary greater than 10000 and age less than 30 years

let employees = [
	{ name: "John", age:30, salary: 5000 },
	{ name: "Bob", age:35, salary: 9000 },
	{ name: "Amy", age:44, salary: 20000},
	{ name: "Alan", age:66, salary: 10000 }
];

let salAgeFilter = {
	age:30, salary: 10000
};

let salary = employees.filter(
	function(elements) {
   	if(elements.salary > salAgeFilter.salary && elements.age > salAgeFilter.age ) 
      {
      	return true;
      }
      return false;
	},
   salAgeFilter
);
console.log(salary);

Output will be:
[{
  age: 44,
  name: "Amy",
  salary: 20000
}]

Advantages of javascript filter function

  • From the above examples we can see that clean code is produced if we use array.filter() function.
  • The original array is not affected by using array.filter() function as the function is returning a new array each time

For More details goto https://developer.mozilla.org/

How do you write a filter function in JavaScript?

Filter function has flowing parameters
1.) element (Optional)-> This is the current element that is being passed
2.) index (Optional)-> This is the index of the current element which is being passed
3.) self (Optional) -> This is the whole array itself.
4.) thisValue (Optional) -> This is the context to be passed as this can be used while executing the callback function.

How does array filter work?

the javascript filter function applies the callback function passed to each element in the array and then decides if to keep or not to keep the element depending on our condition used in the filter is True or False.

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article