Pregunta

I'm trying to use underscores _.groupBy() and _.sortBy in pair, and a problem is that the last one changes object with keys returned from groupBy to array with indexes. Is it possible to preserve original indexes (keys) from object?

Here is example:

My code:

var sorted = _.chain(cars).groupBy('Make').sortBy(function(car) {
    return car.length * -1;
});

Result from groupBy:

{ 
    "Volvo" : [ "S60", "V40" ],
    "Volkswagen" : [ "Polo", "Golf", "Passat" ]
}

Result from sortBy:

[ 
    0 : [ "Polo", "Golf", "Passat" ],
    1 : [ "S60", "V40" ]
]

Expected result:

[
    "Volkswagen" : [ "Polo", "Golf", "Passat" ],
    "Volvo" : [ "S60", "V40" ]
]
¿Fue útil?

Solución

Objects are unordered in JavaScript. If you need something like an object but ordered, you can use _.pairs to convert it, then sort the list of pairs.

_.pairs({ 
    "Volvo" : [ "S60", "V40" ],
    "Volkswagen" : [ "Polo", "Golf", "Passat" ]
})

Gives:

[
    ["Volvo", [ "S60", "V40" ]],
    ["Volkswagen", [ "Polo", "Golf", "Passat" ]]
]

...which you can then sort using _.sortBy. If you assign the above to cars, then:

_.sortBy(cars, function(x) { return -x[0].length; });

gives:

[
    [ 'Volkswagen', ['Polo', 'Golf', 'Passat' ]],
    [ 'Volvo', ['S60', 'V40']]
]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top