Use PHP functions in JavaScript

JavaScript array_filter

Filters elements from the array via the callback.

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
function array_filter (arr, func) {
    // Filters elements from the array via the callback.  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/array_filter    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: Takes a function as an argument, not a function's name
    // *     example 1: var odd = function (num) {return (num & 1);}; 
    // *     example 1: array_filter({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}, odd);
    // *     returns 1: {"a": 1, "c": 3, "e": 5}    // *     example 2: var even = function (num) {return (!(num & 1));}
    // *     example 2: array_filter([6, 7, 8, 9, 10, 11, 12], even);
    // *     returns 2: {0: 6, 2: 8, 4: 10, 6: 12} 
    
    var retObj = {}, k;    
    for (k in arr) {
        if (func(arr[k])) {
            retObj[k] = arr[k];
        }    }
    
    return retObj;
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
2
var odd = function (num) {return (num & 1);};
array_filter({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}, odd);

Should return

1
{"a": 1, "c": 3, "e": 5}

» Example 2

Running

1
2
var even = function (num) {return (!(num & 1));}
array_filter([6, 7, 8, 9, 10, 11, 12], even);

Should return

1
{0: 6, 2: 8, 4: 10, 6: 12}

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have array_filter goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Brett Zamir
18 Aug '09 Permalink

q  Of course that's a typo with array_filter2 (which should just be array_filter)

Gravatar
Brett Zamir
18 Aug '09 Permalink

q   @J: Sorry, no difference. If you set a key on a JS array, it will fill in the gaps with 'undefined'.

Try this with our function:

var arr = array_filter2([3, 4, 5, 6], function (n) {return n >= 5;});
alert(arr.length); // Should be 2, but is 4

Yours gives four, while ours doesn't pretend to be an array (there's no length at all), so it is not confusing.

Gravatar
J
18 Aug '09 Permalink

q   Oops, I meant to put retObj.length to omit the null ones..
Not sure if that makes any diff..

1
2
3
if(!this.is_null(arr[i])){
        retObj[retObj.length] = arr[i];
}

Gravatar
Brett Zamir
17 Aug '09 Permalink

q  Sorry, I meant, "we really have to return an object"

Gravatar
Brett Zamir
17 Aug '09 Permalink

q  @J.: While I know it's definitely tempting to try it that way, a problem arises when the preserved filtered results are not all sequential at the beginning of the array (probably most times); the keys will either end up not being preserved (as they are in PHP), or, as in your code, we'd end up making an array with "undefined" values throughout in place of missing values and which showed a size equal to the original array instead of the length of filter-positive values (as most people would probably want it).

In a number of functions we really have to return an array, though there may be a few which could be adapted to try to return a genuine array where possible. But as far as array_filter, the cases where this would be valid (positive results all sequential at the beginning) would be uncommon, and probably confusing if we didn't follow a uniform policy (unless, again, the results would be consistent).

Gravatar
J.
17 Aug '09 Permalink

q   php handles both array and object, unfortunately JS does not distinguish indexed array and hashed array object...

array_filter in php handles both types and returns type intacted.. Can we add type check like below?

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
40
array_filter: function  (arr, func) {
            var retObj, k, type = 'array';
            func_set = 0;
            
            if(this.isset(func))                func_set = 1;
            // Check for 'length'
            if(arr.length === undefined){
                type = 'hashed_array';
            }            if(type == 'hashed_array'){
                retObj = {};
                    for (k in arr) {
                        if(func_set){
                                if (func(arr[k])) {                                    retObj[k] = arr[k];
                                }
                        }else{
                                if(this.is_null(arr[k]))
                                        continue;                                retObj[k] = arr[k];
                        }
                    }
            }else{
                retObj = [];                for(i=0;i<arr.length;++i){
                        if(func_set){
                                if (func(arr[i])) {
                                    retObj[i] = arr[i];
                                }                        }else{
                                if(this.is_null(arr[i]))
                                        continue;
                                retObj[i] = arr[i];
                        }                }
            }
            
            return retObj;
        }


Contribute a New function