- Posted by liammclennan on June 23, 2009
UPDATE: I have since discovered that these methods are already implemented as part of the jQuery utilities methods.
In C# and Ruby we can use the Where() and Select() methods to select elements from a collection by testing each element with a predicate (method that returns a boolean). Unfortunately, javascript does not have this capability. Here is the code to add a where() method to the javascript array class:
// predicate is a function that accepts one parameter and returns a boolean.
Array.prototype.where = function(predicate) {
var derivedArray = [];
for (i = 0; i < this.length; i += 1) {
if (predicate(this[i])) {
derivedArray.push(this[i]);
}
}
return derivedArray;
});
The prototype property on the Array class is a reference to the object from which all arrays are created, so whatever we add to Array.prototype becomes part of every array that has or will be created. To use the above method:
var evens = [1,2,3,4,5,6,7,8,9,10].where(function(element) {
return element % 2 === 0;
});
// the output from the above method call will be [2,4,6,8,10]
The predicate passed to the where function can be either an anonymous method or a regular method like so:
function isEven(element) {
return element % 2 === 0;
}
var evens = [1,2,3,4,5,6,7,8,9,10].where(isEven);
// the output from the above method call will be [2,4,6,8,10]
Another useful method is called collect or map in ruby and select in C#. Here is the description from the ruby documentation, "Invokes block (anonymous method) once for each element of self. Creates a new array containing the values returned by the block."
Here is a javascript implementation of this method:
// operation is a function that accepts one parameter and returns a value.
Array.prototype.collect = function(operation) {
var derivedArray = [];
for (i = 0; i < this.length; i += 1) {
derivedArray.push(operation(this[i]));
}
return derivedArray;
});
and the usage is:
var doubled = [1,2,3,4,5,6,7,8,9,10].collect(function(element) {
return element * 2;
});
// the output from the above method call will be [2,4,6,8,10,12,14,16,18,20]
The naming of some of these methods is confusing so here is a table explaining the differences.
| |
Selects a subset of the elements of a collection. |
Transforms the elements of a collection. |
| Ruby |
select |
map or collect |
| C# |
Where |
Select |