02 October, 2009

LINQ to Javascript - make a Where

I find LINQ very cool for Data querying.

I tried to code a Where function for Javascript Arrays :

Array.prototype.where = function(condition) {
var list = [];
for (var i=0; i < this.length; i++) {
if ( condition.call(this[i]) ) {
if ( list.length == 1) {
return list[0];
else {
return list;

You havre to send a "condition" function in the where that will test each element and return an array contained elements that verify the condition.

The context of the condition is the element itself so you can easily access it with "this".

Suppose you have INPUT form elements in your document and you want to retrieve those which id contains "browserWidth".

Here is the code :

function() {
return (this.id.indexOf('serviceSelected') != -1);

If the return array contains a single element, it returns the element itself.

No comments: