Skip to content Skip to sidebar Skip to footer

How To Sort Associative Array In Javascript?

I need to sort associative array by JS for one of my projects. I found this function, that works great in firefox, but unfortunately it doesnt work in IE8, OPERA, CHROME... Cant fi

Solution 1:

This is impossible. An Object in JavaScript (which is what you're using as your "associative array") is specified as having no defined order when iterating over its properties using a for...in loop. You may be able to observe some common ground between some browsers' behaviour, but it's not universal.

Summary: if you need objects in a specific order, use an array.

Solution 2:

I know it's an old post but that work :

problem is

aTemp.sort(function () {returnarguments[0][1] < arguments[1][1]});

because the sort function attends a number :

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

Solution 3:

I recently ran into this problem and found this question. I was disappointed to find that there was no pre-defined way to sort an associative array, but it made sense and pointed me in the right direction. I didn't fully realize that in JS associative arrays are really objects and are only arrays in name. I had an associative array that contained more associative arrays, ex:

var firstChild = {'id': 0, 'name': 'company Two'};
var secondChild = {'id': 1, 'name': 'company One'};
var parent = {
    'company Two': firstChild,
    'company One': secondChild
};

The following function will sort the above parent array based upon it's keys. For this to work as written, the parent array needs keys that match a value in the associated array. For instance, parent['unique string'] will need to have some key value that holds a value of 'unique string'. In my case, this is the name key; however, you can choose any key you like.

functionassociativeSort(givenArray, keyToSort) {
    var results = [];

    var temp = [];
    for(var key in givenArray) {
        temp.push(givenArray[key].name);
    }
    temp = temp.sort();
    for(var x = 0; x < temp.length; x++) {
        results[x] = givenArray[temp[x]];
    }

    return results;
}

Given my example array, this function would return:

var parent = {
    'company One': {'id': 1, 'name': 'company One'},
    'company Two': {'id': 0, 'name': 'company Two'}
};

It's a simple solution, but it took me a while to think of. Hope this helps others facing this problem.

Post a Comment for "How To Sort Associative Array In Javascript?"