I have the following code to generate a simple Hash array.
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var arr = [];
for (i=0; i<10; i++) {
var id = 'user-' + Math.floor(getRandomArbitrary(0,1000));
var xp = Math.floor(getRandomArbitrary(2000,3000));
arr[id] = ({'xp':xp});
}
Now to loop through the array I do:
for (id in arr) {
document.write(id + ': ' + arr[id].xp + '<br>');
}
An example result would be:
user-750: 2085
user-681: 2051
user-790: 2174
user-542: 2537
user-943: 2913
user-678: 2829
user-365: 2398
user-886: 2571
user-635: 2525
user-786: 2482
This will show all users and their XP.
The question is, how can I sort this array by XP (descending) ?
I started with:
arr = arr.sort(function(a,b) {
return b.xp - a.xp;
});
But that doesn't work well.
arrisn't an array, it's an object. An array has numeric keys, and.sortonly operates on those elements.