The javascript filter() method creates a new array with all elements that passes the test implemented by the function as an argument returning true result.
Syntax:
var resultArray = givenArray.filter(callback(element, index, array),thisArg)
callback:
Function is a predicate, to test each element of the array. Return true to keep the element otherwise false. It accepts three arguments.
element: The Current element on which is being processed in the array.
index: It is Optional argument, The index of the current element which is being processed in the array.
array: It is Optional argument, On which callback is invoked by filter.
thisArg: It is Optional argument, Value to use as this when executing callback.
Return: A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.
Lets find an array of all the elements having value greater than 10 from a given array.
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
var f = function BiggerThanTen(a)
{
return a>10;
}
var rs = v.filter(f);
document.write(rs);
--OR Using Arrow Operator
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
document.write(v.filter(x=>x>10));
OUTPUT: 23,45,89,45
So javascript filter is short method like LINQ in C# to apply rules over each and every iteration of an array.
To understand callback function of filter method of javascript, lets take few examples.
Retrieve element of an array one by one
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
const f = (e,i,a)=>{return document.write(e+" ");};
var t = v.filter(f);
--OR
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
var t = v.filter(e=>e);
document.write(t);
OUTPUT: 23 45 6 7 8 89 9 5 3 2 1 1 2 45 6 7 5 3 4 6
Retrieve index of element in an array one by one
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
const f = (e,i,a)=>{return document.write(i+" ");};
var t = v.filter(f);
OUTPUT: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Retrieve given array for each iteration
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
const f = (e,i,a)=>{return document.write(a+" ");};
var t = v.filter(f);
OUTPUT: Prints 23 45 6 7 8 89 9 5 3 2 1 1 2 45 6 7 5 3 4 6 19 times.
Lets find distinct elements from an array.
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
var f = function(e,i,a)
{
return a.indexOf(e)==i;
}
var r = v.filter(f);
document.write(r);
--OR Using Arrow Operator
var v = [23,45,6,7,8,89,9,5,3,2,1,1,2,45,6,7,5,3,4,6];
const f = (e,i,a) => {return a.indexOf(e)==i};
var r = v.filter(f);
document.write(r);
OUTPUT: 23,45,6,7,8,89,9,5,3,2,1,4
If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.
Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.