If you’re like me, one of the things you like best about the .NET framework is Language Integrated Query (LINQ), which was added in version 3.5 of the .NET Framework.

Recently, I was working on a simple HTML site using JavaScript to handle data stored in an array. I found that I needed to quickly filter the data based on certain criteria. I started typing a LINQ query, then remembered I was working in JavaScript.  LINQ has, however, been ported to several non-.NET languages, and this includes JavaScript with LINQ to JavaScript.

With LINQ to JavaScript, you have available to you the LINQ functions you’re used to. Now, rather than dealing with loops and counters to filter your data, you can write a simple where clause. This leads to code that’s easier to read and more maintainable.

For example, take a look at the two following snippets.  Both take an input data array, and return only the employees that report to a specific manager.

First, the plain JavaScript:
    var filteredEmps = [];
    for (var i = 0; i && < empData.length; i++) {         var emp = empData[i];         if (emp.Manager == mgrID) {             filteredEmps.push(emp);         }     }     return filteredEmps; }

Now, the same function refactored to use LINQ to JavaScript:

function FilterReports_JSLINQ(empData, mgrID) {
    return JSLINQ(empData).
    Where(function (item) { return item.Manager == mgrID; });

Both get the job done, but the second is more concise and easier to understand.

Not only the Where operator is available. With JSLINQ you will have access to the following LINQ operators:

  • Where
  • Select
  • SelectMany
  • OrderBy
  • OrderByDescending
  • Count
  • Distinct
  • Any
  • All
  • Reverse
  • First
  • FirstOrDefault
  • Last
  • LastOrDefault
  • ElementAt
  • ElementAtOrDefault
  • Concat
  • Intersect
  • DefaultIfEmpty

I highly recommend you download LINQ to JavaScript and give it a try today. It's available on CodePlex.



Like this post? Share it!