Here’s what they say about themselves:
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.
|Special thanks to Adam Anderson for his help with debugging my original underscore code.|
Latest posts by Jesse Liberty (see all)
- Modifying the Xamarin Listbox with Custom Controls - May 26, 2015
- Apple Watch – A Needful Thing - May 23, 2015
- Putting Sitecore data onto your phone with Xamarin - May 22, 2015
- Damn it, can’t you make your code less complex? - May 1, 2015
- Xamarin.Forms: Dynamic Background - April 28, 2015