15.4.4.20 Array.prototype.filter(callbackfn[, thisArg])

2010-07-05

array Array.prototype.filter(callbackfn:function[, thisArg:mixed=undefined])

Call callbackfn once for every element in the array and return a new array containing the elements for which callbackfn returned true. The order of elements is preserved but the index positions is not.

The callback callbackfn should match this fingerprint: mixed function(element:mixed, index:int, object:object).

The this value will be coerced into an object, if thisArg was supplied it is not changed and it is undefined otherwise.

The filter method does not change the array it works on.

The range of filter is determined before actually calling the callbackfn the first time. The value passed on is the value of the array at the time of calling callbackfn (so if callbackfn changes it, the new value is supplied). Deleted elements are skipped. Elements added beyond the initial length of the array during by callbackfn are not processed.

Array.prototype.filter.length = 1

Code: (Meta Ecma)
Array.prototype.filter = function(callbackfn,thisArg){
var O = ToObject(this);
var lenValue = O.[[Get]]("length");
var len = ToUint32(lenValue);
if (!IsCallable(callbackfn)) throw TypeError;
if (arguments.length >= 2) var T = this.arg;
else var T = undefined; // actually, this line is not required ;)
var A = new Array;
var k = 0;
var to = 0;
while (k < len) {
var Pk = ToString(k);
var kPresent = O.[[HasProperty]](Pk);
if (kPresent) {
var kValue = O.[[Get]](Pk);
var selected = callbackfn.[[Call]](T, [kValue, k, O]);
if (ToBoolean(selected)) {
A.[[DefineOwnProperty]](ToString(to), PD{[[Value]]:kValue, [[Writable]]:true, [[Enumerable]]:true, [[Configurable]]:true}, false);
++to;
}
}
++k;
}
return A;
}