Naghaveer R
Naghaveer R

Reputation: 2944

Javascript : Sort Associative array using value property without converting into Array of objects

I need to sort associative array by value (using "position" value as shown below). I tried by converting into array. It is working fine. But I wanted to know, Is there any other way of doing it?

{  
   "CAB":{
           name:CBSSP,
           position:2
         },
   "NSG":{  
           name:NNSSP,
           position:3
         },
   "EQU":{  
           name:SSP,
           position:1
         }
}

Upvotes: 0

Views: 62

Answers (3)

Dhananjaya Kuppu
Dhananjaya Kuppu

Reputation: 1322

You could also try:

Object.keys(o).map(function(key){return o[key];})
              .sort(function(p, c){return  p.position - c.position})

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386570

You can use an order array for the ordered reference to the object. You need a correction of position, because arrays are zero based.

var object = { "CAB": { name: 'CBSSP', position: 2 }, "NSG": { name: 'NNSSP', position: 3 }, "EQU": { name: 'SSP', position: 1 } },
    order = [];

Object.keys(object).forEach(function (k) {
    return order[object[k].position - 1] = k;
});

document.write('<pre>' + JSON.stringify(order, 0, 4) + '</pre>');

Upvotes: 0

MrCode
MrCode

Reputation: 64526

There is no associative array in JavaScript, what you have is an object, with properties CAB, NSG and EQU.

Object properties can't guarantee a set order, so the solution is to use an array of objects because arrays do indeed guarantee the order.

Upvotes: 0

Related Questions