JavaScript Array filter

The JavaScript Array filter method creates a new array by filtering out the elements of an existing array using a callback function.

Syntax

var filteredArray = array.filter(callback [, contextObject])

Parameters

callback
The callback function to use
contextObject
Object to be used as a context for the callback function

Description

The JavaScript Array filter method iterates over each value of an array passing it to a callback function. If the callback function returns true, the current value is then pushed into the resulting array.

The callback function is invoked with three arguments: the value of the element, the index of the element and the Array object being traversed.

Bellow is an example of filtering odd and even numbers out of an array:

var arr = [1, 2, 3, 4, 5];
var odd = arr.filter(function(val) {
	return 0 != val % 2;
});
// odd = [1, 3, 5]
var even = arr.filter(function(val) {
	return 0 == val % 2;
});
// even = [2, 4]

The Array filter method can also be used to remove empty, null or undefined elements from an array:

var arr = [0, null, 42, undefined, "", true, false, NaN, "", "foo bar"];
var filteredArr = arr.filter(function(val) {
	return !(val === "" || typeof val == "undefined" || val === null);
});
// filteredArr = [0, 42, true, false, NaN, "foo bar"]

Cross-browser Array filter

For browsers that don't support the Array filter method, here's an alternative implementation:

/**
 * Copyright (c) Mozilla Foundation http://www.mozilla.org/
 * This code is available under the terms of the MIT License
 */
if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();
        }

        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                var val = this[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, this)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}

See also

If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.

Copyright © 2010-2013 Dive Into JavaScript