Javascript Array Filter Method

Posted By : Vinay Tiwari | 28-Feb-2018
In this blog, we are going to be learning about filter methods of an array in javascript. The filter() method creates a new array and populates that array with all elements that meet the condition specified in a callback function.
 
Syntax :- array.filter(callbackFunction[,thisArg])
 
This method has two parameters callbackFunction & thisArg
 
callbackFunction is a required parameter, this callback Function gets called for each element of the array. If the function returns true, the element is kept otherwise filtered.
The second parameter that is thisArg is an optional parameter within this callback function we can use 'this' keyword the object that 'this' keyword references can be specified using the second parameter (thisArg). 
 
The filter method calls the callbackFunction one time for each element in the array. In case the callback function returns false for all elements of the array, the length of the new array which will be returned would be zero.
 
Callback Function syntax 
the Callback function it has got three parameters value, index, array. 
function callbackFunction(value, index, array)
 
Let's look at an example
var myArray = ["Sam", "Mark", "Sam", "Param", "Sam"];
var result = myArray.filter(function(value, index, array){
	return array.indexOf(value) == index;
});
document.write(result);
// 'result' is Sam, Mark, Param
 
Declaration:-
 
In this example, array going to contain a string. "Sam" is repeated many of times in this array. We want to do is the filter of duplicate elements in this array. 
We want to get only the unique elements of the array. So, let see how to achieve this using the filter() method. The Callback Function() will have those three parameters value, index and array. So, here 'array' parameter is referencing the source array that contains the element that we want to filter. this method 
(array.indexOf(value)) is going to return us the index of the given element and going to compared that 'index' parameter. And both methods are going to be equal index value it will return true & otherwise it will return false. It will remove the duplicates elements from a Javascript array.

 

Thanks

 

About Author

Author Image
Vinay Tiwari

Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.

Request for Proposal

Name is required

Comment is required

Sending message..