Ben Siver Ben Siver - 2 months ago 18
Javascript Question

Maintaining sort order using underscore's groupBy()

I have an array of simple objects that looks like the following:

var objects =[
{
"group": "05",
"format": "Legacy",
"active": false
},
{
"group": "05",
"format": "Legacy",
"active": false
},
{
"group": "23",
"format": "Legacy",
"active": true
}
]


I would like to use underscore's groupBy function to group these items, while maintaining the order of the attribute being grouped by.

When calling
_.groupBy(objects, 'group')
, the result looks like this:

{
"23": [
{
"group": "23",
"format": "Legacy",
"active": true
}
],
"05": [
{
"group": "05",
"format": "Legacy",
"active": false
},
{
"group": "05",
"format": "Legacy",
"active": false
}
]
}


Is there a particular reason the '23' grouping gets placed in the resultant object before '05'? It doesn't seem to respect either natural ordering or the order of the array being grouped on.

Answer

You can consider the result of _.groupBy a hashtable, since Objects in JS are usually implemented as unordered hashtables for constant time retrieval of property values etc.

Javascript hashtable implementations should not guarantee the sorting order of the keys, so you can't count on sorting when using them.

Per the comments by @mu is too short, that doesn't mean that in the future some ES* implementation won't have ordered hashtables.

Comments