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 Falafel Posts (see all)
- Matching Complex Query String Rewrite Rule in IIS - March 22, 2017
- Disable Content Filters in Sitefinity - March 8, 2017
- On Sitefinity Custom Widget Caching - February 22, 2017
- Dynamic Content Detail Widget Templates in Sitefinity - February 8, 2017
- Using Google Services in UWP C# Apps – Part 2 - February 7, 2017