Search code examples
angularsortingunderscore.jslodash

lodash - sort result of _.groupBy before creating an array with it


I'm using lodash's groupBy to group objects by a number value which can be 1 - 10. Let's call the property "sort"

the result of the groupBy looks like

{
    1:[{sort:1,...}, ...],
    2:[{sort:2,...}], ...].
    ...
}

Next I use Object.values(result) to convert it back into a 2 dimensional array for displaying it in angular with a double ngFor.

The thing is that I can't be certain (can I?) that the order of the object well be in order. Does the groupBy creates the keys in first-fit order?

So in case the result looks like

{
    3:[...],
    1:[...],
    2:[...],
    ...
}

How presort the _groupBy result before pushing it to an array?


Solution

  • I tend to have a hard time trusting the iteration order of JavaScript objects as well. I suggest you remove the uncertainty by using lodash's sortBy function for collections.

    If I've interpreted your question correctly, applying sortBy to your result object (using the _.property iteratee shorthand) should give you the 2D array structure you're looking for:

    this.target_data = _.sortyBy(result, 'sort');
    

    this.target_data becomes a 2D array: the first row is a list of objects of sort = 1, the next is a list of objects of sort = 2, etc.

    Please see this quick demo.