Javascript natural sort array / object and maintain index association

I have an array of elements as indicated 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 to sort this array to get the following result:

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

Notice how it is sorted by array value, and the value-to-index association is maintained after the array is sorted (which is critical). I was looking for a solution to this, tried to do it, but hit a wall.

By the way, I know that this is technically not an array, since this means that the indices always repeat from 0 to n, where n + 1 is the account number n. However, you determine this, the requirement for the project remains the same. Also, if that matters, I am NOT using jquery.

+5
7

, . naturalSort - , google, . , , , - . :

users[0][0] = 72;
users[0][1] = 'testuser4';
users[1][0] = 91;
users[1][1] = 'testuser2';
users[2][0] = 12;
users[2][1] = 'testuser8';
users[3][0] = 3;
users[3][1] = 'testuser1';
users[4][0] = 18;
users[4][1] = 'testuser7';
users[5][0] = 47;
users[5][1] = 'testuser3';
users[6][0] = 16;
users[6][1] = 'testuser6';
users[7][0] = 20;
users[7][1] = 'testuser5';

, :

users_sorted[0][0] = 3;
users_sorted[0][1] = 'testuser1';
users_sorted[1][0] = 91;
users_sorted[1][1] = 'testuser2';
users_sorted[2][0] = 47;
users_sorted[2][1] = 'testuser3';
users_sorted[3][0] = 72;
users_sorted[3][1] = 'testuser4';
users_sorted[4][0] = 20;
users_sorted[4][1] = 'testuser5';
users_sorted[5][0] = 16;
users_sorted[5][1] = 'testuser6';
users_sorted[6][0] = 18;
users_sorted[6][1] = 'testuser7';
users_sorted[7][0] = 12;
users_sorted[7][1] = 'testuser8';

:

function naturalSort(a, b) // Function to natural-case insensitive sort multidimensional arrays by second index
{

    // setup temp-scope variables for comparison evauluation
    var re = /(-?[0-9\.]+)/g,
        x = a[1].toString().toLowerCase() || '',
        y = b[1].toString().toLowerCase() || '',
        nC = String.fromCharCode(0),
        xN = x.replace( re, nC + '$1' + nC ).split(nC),
        yN = y.replace( re, nC + '$1' + nC ).split(nC),
        xD = (new Date(x)).getTime(),
        yD = xD ? (new Date(y)).getTime() : null;
    // natural sorting of dates
    if ( yD )
        if ( xD < yD ) return -1;
        else if ( xD > yD ) return 1;
    // natural sorting through split numeric strings and default strings
    for( var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++ ) {
        oFxNcL = parseFloat(xN[cLoc]) || xN[cLoc];
        oFyNcL = parseFloat(yN[cLoc]) || yN[cLoc];
        if (oFxNcL < oFyNcL) return -1;
        else if (oFxNcL > oFyNcL) return 1;
    }
    return 0;
}

// Set values for index
    var users = Array();
    var temp = Array();

    users.push(Array('72', 'testuser4'));
    users.push(Array('91', 'testuser2'));
    users.push(Array('12', 'testuser8'));
    users.push(Array('3', 'testuser1'));
    users.push(Array('18', 'testuser7'));
    users.push(Array('47', 'testuser3'));
    users.push(Array('16', 'testuser6'));
    users.push(Array('20', 'testuser5'));

// Sort the array
    var users_sorted = Array();
    users_sorted = users.sort(naturalSort);
+2

. , , , undefined - undefined:

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

, , , , , :

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

:

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

:

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

, , , . ,

// Don't do this!
var array = new Array();
array[0] = 'value';
array[1] = 'value';
array[2] = 'value';

. - , . :

var array = [
    'value',
    'value',
    'value'
]

, . users[562] = 'testuser3' , 562 , 563- .

- . , , , JavaScript :

var users = {
    562: 'testuser3',
    16:  'testuser6',
    834: 'testuser1',
    823: 'testuser4',
    23:  'testuser2',
    917: 'testuser5'
}

, . galambalazs, :

var userOrder;
if (typeof Object.keys === 'function') {
    userOrder = Object.keys(users);
} else {
    for (var key in users) {
        userOrder.push(key);
    }
}

... :

userOrder.sort(function(a, b){
    return users[a].localeCompare(users[b]);
});

+7

Javascript. .

order = new Array();
order[0] = 562;
order[1] = 16;
order[2] = 834;
order[3] = 823;
order[4] = 23;
order[5] = 917;

, , , . , .

order.sort( function(a, b) {
  if ( users[a] < users[b] ) return -1;
  else if ( users[a] > users[b] ) return 1;
  else return 0;
});

for ( var i = 0; i < order.length; i++ ) {
  // users[ order[i] ]
}

[]

+3

, , , .

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

var u2= [];
users.map(function(itm, i){
    if(itm){
        var n= parseInt(itm.substring(8), 10);
        u2[n]= i;
    }
});
u2.map(function(itm, i){
    return 'users['+itm+']= testuser'+i;
}).join('\n');

/*returned value: (String)
users[834]= testuser1
users[23]= testuser2
users[562]= testuser3
users[823]= testuser4
users[917]= testuser5
users[16]= testuser6
*/

. -

u2.map(function(itm, i){
    return 'users['+itm+']= testuser'+i;
}).filter(function(itm){return itm}).join('\n');
+1

. - ( JSON):

users = [{
    "562": "testuser3"
},{
    "16": "testuser6"
}, {
    "834": "testuser1"
}, {
    "823": "testuser4"
}, {
    "23": "testuser2"
}, {
    "917": "testuser5"
}];

, for .

+1

Array.prototype.sort() , , users [ [562, "testuser3"], [16, "testuser6"] ... etc.]

sort :

function(comparatorA, comparatorB) {
    var userA = comparatorA[1], userB = comparatorB[1]
    if (userA > userB)     return 1;
    if (userA < userB)     return -1;
    if (userA === userB)   return 0;
}

Then rebuild your object users. (This will save you from sorting.) Or save the data in a newly sorted array of arrays if this works for your application.

0
source

All Articles