0

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
         }
}

3 Answers 3

1

You could also try:

Object.keys(o).map(function(key){return o[key];})
              .sort(function(p, c){return  p.position - c.position})
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

"Object properties can't guarantee a set order," - not in Javascript.
0

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>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.