Javascript Array Filter Method
Posted By : Vinay Tiwari | 28-Feb-2018
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
Request for Proposal
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.