Converting an object literal to a sorted Array

arrays, javascript, sorting

Solution

Example:

var data = {
    foo: {
        rank: 5
    },
    bar: {
        rank: 2
    },
    baz: {
        rank: 8
    }
};

Javascript:

var mappedHash = Object.keys( data ).sort(function( a, b ) {
    return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
    return data[ sortedKey ];
});

That would first `sort` the inner objects by the value of `obj.rank` and after that `map` the containing objects into an Array.

Result: `[{rank: 2}, {rank: 5}, {rank: 8}]`

Reference: `Object.keys`, `Array.prototype.sort`, `Array.prototype.map`

The above code contains ECMAscript 262 edition 5 code, which is available in all modern browsers. If you want to support legacy browsers as well, you need to include one of the various ES5-Shim libraries.

Problem

I have an object literal, where the values of its key are more objects, and one of the keys of the inner objects is named "rank" - and has an floating point value. I want to convert the object literal to an array of the inner objects, sorted by the value of "rank". Input Object: ``` { 452:{ bla:123, dff:233, rank:2 }, 234:{ bla:123, dff:233, rank:1 } ``` } Output Array: ``` [ { bla:123, dff:233, rank:1}, { bla:123, dff:233, rank:2 } ] ```

Original source