Javascript natural sort array/object and maintain index association -


i have array of items follows in javascript:

var users = array();  users[562] = 'testuser3'; users[16] = 'testuser6'; users[834] = 'testuser1'; users[823] = 'testuser4'; users[23] = 'testuser2'; users[917] = 'testuser5'; 

i need sort array following output:

users[834] = 'testuser1'; users[23] = 'testuser2'; users[562] = 'testuser3'; users[823] = 'testuser4'; users[917] = 'testuser5'; users[16] = 'testuser6'; 

notice how sorted value of array , value-to-index association maintained after array sorted (that critical). have looked solution this, tried making it, have hit wall.

by way, aware technically not array since mean indices iterating 0 through n n+1 counting number proceeding n. define it, requirement project still same. also, if makes difference, not using jquery.

the order of elements of array defined index. if specify values in different order, values stored in order of indices , undefined indices undefined:

> var arr = []; > arr[2] = 2; > arr[0] = 0; > arr [0, undefined, 2] 

now if want store pair of index , value, need different data structure, maybe array of array this:

var arr = [     [562, 'testuser3'],     [16, 'testuser6'],     [834, 'testuser1'],     [823, 'testuser4'],     [23, 'testuser2'],     [917, 'testuser5'] ]; 

this can sorted comparison function:

function cmp(a, b) {     return a[1].localecompare(b[1]); } arr.sort(cmp); 

the result array:

[     [834, 'testuser1'],     [23, 'testuser2'],     [562, 'testuser3'],     [823, 'testuser4'],     [917, 'testuser5'],     [16, 'testuser6'] ] 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -