0

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

1
  • 5
    Objects have no particular order, you want an array... Commented Oct 14, 2013 at 21:39

2 Answers 2

2

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]});
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the answer, can you please tell how to iterate over usernames to fetch key and username
1
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);
})

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.