--- warning: 'This file is auto generated by `npm run web:inject`, do not edit by hand' examples: - |- var odd = function (num) {return (num & 1);} array_filter({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}, odd) - |- var even = function (num) {return (!(num & 1));} array_filter([6, 7, 8, 9, 10, 11, 12], even) - >- array_filter({"a": 1, "b": false, "c": -1, "d": 0, "e": null, "f":'', "g":undefined}) estarget: es5 returns: - '{"a": 1, "c": 3, "e": 5}' - '[ 6, , 8, , 10, , 12 ]' - '{"a":1, "c":-1}' dependencies: [] authors: original by: - 'Brett Zamir (http://brett-zamir.me)' improved by: - 'Brett Zamir (http://brett-zamir.me)' input by: - max4ever notes: - 'Takes a function as an argument, not a function''s name' type: function layout: function title: PHP's array_filter in JavaScript description: >- Here’s what our current JavaScript equivalent to PHP's array_filter looks like. function: array_filter category: array language: php permalink: php/array/array_filter/ alias: - /functions/php/array_filter/ - /functions/array/array_filter/ - /php/array_filter/ - /functions/array_filter/ --- {% codeblock lang:javascript %}module.exports = function array_filter (arr, func) { // eslint-disable-line camelcase // discuss at: http://locutus.io/php/array_filter/ // original by: Brett Zamir (http://brett-zamir.me) // input by: max4ever // improved 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: [ 6, , 8, , 10, , 12 ] // example 3: array_filter({"a": 1, "b": false, "c": -1, "d": 0, "e": null, "f":'', "g":undefined}) // returns 3: {"a":1, "c":-1} var retObj = {} var k func = func || function (v) { return v } // @todo: Issue #73 if (Object.prototype.toString.call(arr) === '[object Array]') { retObj = [] } for (k in arr) { if (func(arr[k])) { retObj[k] = arr[k] } } return retObj } {% endcodeblock %}