Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an object literal to a sorted Array

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 }
]
like image 258
Daniel Avatar asked Dec 04 '12 01:12

Daniel


2 Answers

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.

like image 162
jAndy Avatar answered Oct 23 '22 01:10

jAndy


Iterate over your object's properties, pushing the inner objects into an array, and then sort the array with a custom sort function:

var inputObject = {}, // your object here
    arr = [];

for (var k in inputObject)
    arr.push(inputObject[k]);

arr.sort(function(a,b) { return a.rank - b.rank; });
like image 1
nnnnnn Avatar answered Oct 23 '22 02:10

nnnnnn