Latest posts.

Javascript Array Filtering

In my last post, I presented a javascript function to convert a C# style lambda expression into a function as part of a library that provides functionality similar to Linq.

Today I’ll add a method for filtering. Linq has a where clause, so I’ll add a where method, callable through the Array prototype.

To specify the filter criteria, I’ll pass a function or lambda expression. I’ll also include support for passing extra parameters through to the filter function.

Our where method signature looks like this:

var where( filter, param,...);

where filter is a function or lambda string and param represents parameters passed through to the filter function.

Our filter function signature looks like this:

var filter( el, i, res, params,... );

where el is the value of the element from the array specified by index, i is the current index, res is the array of filtered elements, and params represents the extra parameters passed to the where call.

More… »

Javascript Lambda Expressions

I’ve been working with Linq lately and wished that I could use it in other languages. Since I code in Javascript a good bit and it’s a prototype language, I figured I could add the Linq functionality to the Javascript Array object through it’s prototype.

I’ll start with my target, which is the ability to do something like:

var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ] ;     
// use lambda expression to filter out odd numbers
var a2 = a.where( "( n ) => n % 2 == 0" );

First, I need to parse out the C# style Lambda expression into function arguments and body.

The following regular expression should do the trick:


In a nutshell: look for an open parenthesis, skip it, capture everything that isn’t a close parenthesis and save it. Then skip the close parenthesis, ‘=>’ and white space and capture everything that’s left.
More… »