You sometimes need to use Javascript’s Object() as an associative array to store more data? But than you lose that array.sort() function.. If you know what I mean, than here’s the solution.
A small function to sort a Javascript Object() by value. There are a lot of sorting algorithms, like for instance Insertion sort, but we’ll use the simplest one, and that is Bubble sort.
I’m not going to explain how it works, if you’re interested check the link above or catch a video on Algorithm basics on MIT video.
So, the code.
/*
a simple bubble sort algorithm on an object
*/
function bubbleSortObject(object) {
for (i in object) {
for (k in object) {
if (object[i] < object[k]) {
var temp = object[i];
object[i] = object[k];
object[k] = temp;
}
}
}
return object;
}
var numbers = new Object({'item1': 12345, 'item2': 98765, 'item3': 0.00001});
var result = bubbleSortObject(numbers);
Hope it helps
You’re destroying the key-value relationship.
{‘item1′: 12345, ‘item2′: 98765, ‘item3′: 0.00001}
becomes
{“item1″:0.00001,”item2″:12345,”item3″:98765}
thanks a lot, Its working great.