The filter()
function is used to take elements out of an array. The callback must return True
(to include the item in the new array) or False
(to drop it). Something similar could be achieved by using the map()
function and returning a null
value for items you want dropped, but the filter()
function will delete the item from the new array instead of inserting a null
value in its place.
Syntax: arr.filter(callback [, thisArg]);
Parameters:
callback()
: This function is used to test each element in the array. Return True
to keep the element, False
otherwise. With these parameters:currentValue
: This parameter gives the current element being processed in the arrayindex
: This parameter gives the index of the current element in the arrayarray
: This parameter gives the array being processed.thisArg()
: This function is optional. Value is used as this
when executing callback
.Examples:
var myarray = [1,2,3,4] words = 'hello 123 world how 345 ya doing'.split(' '); re = '[a-zA-Z]'; // remove all negative numbers console.log([-2,-1,0,1,2].filter(function(x){return x>0})); // remove null values after a map operation console.log(words.filter(function(s){ return s.match(re); }) ); // remove random objects from an array console.log(myarray.filter(function(){ return Math.floor(Math.random()*2)}) );