Question

I want to sort an object which is associative in terms (key, value) I am able to store the values according to the key, but unable to sort them on the basis of value using in-built sort() functions as in case of associative array.

var usernames = {};

username[1] = "ZNAME";
username[2] = "BNAME";
username[3] = "ANAME";
username[4] = "TNAME";
username[5] = "KNAME";
username[5] = "YNAME";

$.each(usernames,function(key, value){
    alert(key + " : " + value);
})

Please tell the method to sort with my updated JSFIIDLE

DEMO

Was it helpful?

Solution

You can't sort an object, you have to make it an array. For example:

var usernamesArray = [
    {key:1,username:"ZNAME"},
    {key:2,username:"BNAME"},
    ...
    {key:5,username:"YNAME"}
];
var sortedUsernamesArray=usernamesArray.sort(function(a,b){
    //
    return (a.username>b.username)?1:-1;
});

Live demo: http://jsfiddle.net/GrD4v/

Note: jQuery is not needed here.

[Edit] There are a couple different ways to build the usernamesArray. A simple one:

var usernamesObject = {};
var usernamesArray = [];

usernamesObject[1] = "ZNAME";
usernamesObject[2] = "BNAME";
usernamesObject[3] = "ANAME";
usernamesObject[4] = "TNAME";
usernamesObject[5] = "KNAME";
usernamesObject[6] = "YNAME";

for (var i=1;i<7,i++) {
    usernamesArray.push({key:i,username:usernamesObject[i]});
}

OTHER TIPS

var username = [];

username[0] = "ZNAME";
username[1] = "BNAME";
username[2] = "ANAME";
username[3] = "TNAME";
username[4] = "KNAME";
username[5] = "YNAME";

username.sort();

$.each(username,function(key, value){
    alert(key + " : " + value);
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top