Javascript sort Object by value

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 ;)

This entry was posted in A chunk of code and tagged , , . Bookmark the permalink.

2 Responses to Javascript sort Object by value

  1. AC says:

    You’re destroying the key-value relationship.

    {‘item1′: 12345, ‘item2′: 98765, ‘item3′: 0.00001}
    becomes
    {“item1″:0.00001,”item2″:12345,”item3″:98765}

  2. hitesh anjara says:

    thanks a lot, Its working great.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>