With the underscore function groupBy, an array can be grouped by one of its element's properties. The result is an object which has key-value pairs as followed: group > corresponding array fragment.
var words = ['Hey', 'Hii', 'Salut'],
grouped = _.groupBy(words, 'length');
grouped looks like this:
{
'3': ['Hey', 'Hii'],
'5': ['Salut']
}
Which would be a simple and secure way to iterate over this, say starting with the highest length followed by the next lowest. This works:
_.each( _.toArray(grouped).reverse(), function(v) {
console.log(v);
} );
But I think it's not totally correct, because objects are unordered lists, and the right order happens here just by chance. Any comments on this?
_.groupBy(collection, [iteratee=_.identity]) Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection.
groupBy() groups the items into a plain JavaScript object, while array. groupByToMap() groups them into a Map instance. If you'd like to use these functions right away, then use the polyfill provided by core-js library.
You are right in that you cannot rely on the object keys sorting, you need to enforce the right sorting. With underscore you can use _.sortBy
:
_.each(
_.sortBy(
_.toArray(grouped), function (num) {
return num;
}
).reverse(),
function (v) {
console.log(v);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With