Underscore: LINQ (almost) for JavaScript

By March 5, 2014Uncategorized

As part of my emerging series on LINQ from Scratch, I’d like to take a small detour today into what you do if you need the functionality of LINQ in your JavaScript program.   One answer is the underscore.js library

Here’s what they say about themselves:

Underscore provides 80-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers: function binding, JavaScript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of forEach, map, reduce, filter, every, some and indexOf.

I just wanted to do a query against some data in memory, and underscore was the perfect answer. 

The data I had consisted of a series of books and I wanted to filter out all but the best in each genre, to use with KendoUI.  To do so, I needed to create a collection of filters for all the books that were not the highest rated in their genre. 

As you can see, the data consisted of a small set of books, each with a rating.  My goal was to find all but the highest rated books in each genre and create a filter object for them.  To do this, I used underscore in a series of steps.

_.sortBy was passed my entire data set, and sorted based on the book’s rating. I called reverse() on the resulting array to have the highest rated book listed first.

_.groupBy was passed that reverse-sorted collection to group by the genre. The result was an underscore object that contained a collection of keys (genres) and an associated array of books. I needed this to be in the form of a collection so I called _.map, passing in that object and getting back an array of arrays.  The function I passed to _.map, _.rest, excluded the first member of each array (the highest rated). 

What I got back from _.map was an array of arrays so I called _.flatten to turn that into a single dimension array.  I could then iterate over the array using _.each to create my filters.

There is much more you can do, but you can see very quickly that much of the functionality you would get from LINQ is available to JavaScript programmers through this library.

Special thanks to Adam Anderson for his help with debugging my original underscore code.
The following two tabs change content below.