A Stage 0 proposal to add Array.prototype.select and
Array.prototype.reject.
const array = [1, 2, 3, 4, 5];
// Select is just an alias for Array.p.filter
array.select(i => (i < 3)); // => [1, 2];
// Reject does the opposite of select.
array.reject(i => (i < 3)); // => [3, 4, 5];Array.prototype.filter is confusing. I constantly have to ask myself
"am I filtering in, or filtering out the current item?".
- "Filtering in"
-
Implies that returning
truewould keep the current item. - "Filtering out"
-
Implies that returning
truewould remove the current item.
Array.p.filter acts as "filtering in". But when I think of the word
"filter", I think of "filtering out". So every time that I attempt to
write an array filter, I end up writing the opposite of what I intended.
Array.p.select fixes this confusion. You are selecting the current
item. Similarly, Array.p.reject means you are rejecting the current
item.
The initial value of the select property is the same function object
as the initial value of the Array.prototype.filter property.
When the reject method is called with one or two arguments, the
following steps are taken:
- Let
Obe? ToObject(this value). - Let
lenbe? LengthOfArrayLike(O). - If
IsCallable(callbackfn)isfalse, throw aTypeErrorexception. - If
thisArgis present, letTbethisArg; else letTbeundefined. - Let
Abe? ArraySpeciesCreate(O, 0). - Let
kbe 0. - Let
tobe 0. - Repeat, while
k<len- Let
Pkbe! ToString(k). - Let
kPresentbe? HasProperty(O, Pk). - If
kPresentistrue, then- Let
kValuebe? Get(O, Pk). - Let
rejectedbe! ToBoolean(? Call(callbackfn, T, « kValue, k, O »)). - If
rejectedisfalse, then- Perform
? CreateDataPropertyOrThrow(A, ! ToString(to), kValue). - Set
tototo + 1.
- Perform
- Let
- Set
ktok + 1.
- Let
- Return
A.
- Ruby
- Underscore
- Lodash