Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort my JSON array?

How to output this JSON element in correct order by it's value?

var json = { 
    "message": {
        "90": "Adidas", 
        "2": "Armani", 
        "89": "Casio", 
        "1": "Diesel", 
        "72": "DKNY", 
        "88": "Fossil", 
        "4": "Hamilton", 
        "6": "Luminox", 
        "99": "Michael Kors", 
        "968": "Mont Blanc Pens", 
        "3": "Nixon", 
        "959": "Nooka", 
        "92": "Seiko", 
        "91": "Tendence", 
        "7": "Tissot" 
    } 
};

var str = '';
for (var i in json.message) {
    str += json.message[i]+'\n';
}
alert(str);

it alerts in the below order -

Diesel
Armani
Nixon
Hamilton
Luminox
DKNY
Fossil
Casio
Adidas
Tendence
Seiko
Michael Kors
Nooka
Mont Blanc Pens

But I want it in below order

Adidas
Armani
Casio
Diesel
DKNY
Fossil
Hamilton
Luminox
Michael Kors
Mont Blanc Pens
Nixon
Nooka
Seiko
Tendence
Tissot

Can any one suggest me what approach I should adopt to get in correct order?

Any help would be greatly appreciated!

like image 872
Vikas Naranje Avatar asked Jan 18 '23 18:01

Vikas Naranje


1 Answers

Assuming you want the elements listed in alphabetical order by their value:

var values = [];
for(var i in json.message) {
   values.push(json.message[i]);
}
var str = values.sort().join('\n');

Update

To form an array of key-value pairs ordered by their (string) value:

var values = [];
for(var i in json.message) {
   values.push({ key: i, value: json.message[i] });
}
values.sort(function(a, b) { return a.value.localeCompare(b.value); });
var str = values.map(function (kvp) { return kvp.value; }).join('\n');
like image 77
Rich O'Kelly Avatar answered Jan 20 '23 08:01

Rich O'Kelly