Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate over an object retrieved from _.groupBy

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?

like image 912
Anton Harald Avatar asked Sep 06 '15 21:09

Anton Harald


People also ask

What is groupBy in Lodash?

_.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.

What is Groupby in JavaScript?

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.


1 Answers

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);
    }
);
like image 170
Andrea Casaccia Avatar answered Sep 22 '22 12:09

Andrea Casaccia