Javascript Equivalent for PHP array_filter() function

by Sasikumar 2014-03-04 09:39:39

The following function is the javascript equivalent for the php array_filter() function,
function array_filter(arr, func)
{
var retObj = {},k;
func = func || function(v) { return v; };
if (Object.prototype.toString.call(arr) === '[object Array]') { retObj = []; }
for (k in arr)
{
if (func(arr[k])) { retObj[k] = arr[k]; }
}
return retObj;
}
Some examples for the usage of the function,
Example :
var even = function (num) {return (!(num & 1));}
array_filter([6, 7, 8, 9, 10, 11, 12], even);
ouput:
{0: 6, 2: 8, 4: 10, 6: 12} //returns even numbers alone

Note :The argument for the function is an array and a function to define the process. The function can be NULL
829
like
0
dislike
0
mail
flag

You must LOGIN to add comments