Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a great use case for the <em>reduce</em> phase of <em>map-reduce</em>. It's not going to be as visually elegant as the multi-group function (you can't just pass in an array of keys to group on), but overall this pattern gives you more flexibility to transform your data. <a href="http://jsfiddle.net/tynman/djQnD/1/" rel="nofollow" title="EXAMPLE">EXAMPLE</a></p> <pre><code>var grouped = _.reduce( properties, function(buckets, property) { // Find the correct bucket for the property var bucket = _.findWhere(buckets, {size: property.size, category: property.category}); // Create a new bucket if needed. if (!bucket) { bucket = { size: property.size, category: property.category, items: [] }; buckets.push(bucket); } // Add the property to the correct bucket bucket.items.push(property); return buckets; }, [] // The starting buckets ); console.log(grouped) </code></pre> <p>But if you just want it in an underscore mixin, here's my stab at it:</p> <pre><code>_.mixin({ 'groupAndSort': function (items, sortList) { var grouped = _.reduce( items, function (buckets, item) { var searchCriteria = {}; _.each(sortList, function (searchProperty) { searchCriteria[searchProperty] = item[searchProperty]; }); var bucket = _.findWhere(buckets, searchCriteria); if (!bucket) { bucket = {}; _.each(sortList, function (property) { bucket[property] = item[property]; }); bucket._items = []; buckets.push(bucket); } bucket._items.push(item); return buckets; }, [] // Initial buckets ); grouped.sort(function (x, y) { for (var i in sortList) { var property = sortList[i]; if (x[property] != y[property]) return x[property] &gt; y[property] ? 1 : -1; } return 0; }); return _.map(grouped, function (group) { var toReturn = { key: {}, value: group.__items }; _.each(sortList, function (searchProperty) { toReturn.key[searchProperty] = group[searchProperty]; }); return toReturn; }); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload