Javascript Sorting - Example 7

Advanced sorting

This page demostrates the use of a comparison function with the Javascript sort method. The function will perform a sort on the item element in two objects in the array.

For more information return to the article "Sort Your Data with Javascript".

Example code

// Define objects for test
var testObject1 = {title: "Star City",
                   link: "",
                   description: "How do Americans get ready to work with Russians aboard the space station?",
                   pubDate: "Tue, 03 Jun 2003 09:39:21 GMT", 
                   guid: ""};
var testObject2 = {title: "Space Exploration",
                   link: "",
				   description: "Sky watchers in Europe, Asia, and parts of Alaska and Canada will experience a partial eclipse of the Sun on Saturday, May 31st.",
				   pubDate: "Fri, 30 May 2003 11:06:42 GMT", 
				   guid: ""};
var testObject3 = {title: "The Engine That Does More",
                   link: "",
				   description: "Before man travels to Mars, NASA hopes to design new engines that will let us fly through the Solar System more quickly.  The proposed VASIMR engine would do that.",
				   pubDate: "Tue, 27 May 2003 08:37:32 GMT", 
				   guid: ""};
var testObject4 = {title: "Astronauts' Dirty Laundry",
                   link: "",
				   description: "Compared to earlier spacecraft, the International Space Station has many luxuries, but laundry facilities are not one of them. Instead, astronauts have other options.",
				   pubDate: "Tue, 20 May 2003 08:56:02 GMT", 
				   guid: ""};
var testObject5 = {title: "Why Google circles are likely to fail",
                   link: "",
				   description: "I write a lot. More than most. And I have been doing it for a long time.",
				   pubDate: "Fri, 01 Jul 2011 12:47:32 GMT", 
				   guid: ""};
// Add objects to testArray
testArray[testArray.length] = testObject1;
testArray[testArray.length] = testObject2;
testArray[testArray.length] = testObject3;
testArray[testArray.length] = testObject4;
testArray[testArray.length] = testObject5;
// Create a comparison function to sort on the pubDate element in each object
function comparepubDates(a, b) {
var pubDateValue1 = Date.parse(a.pubDate); // Get milliseconds for date/time string
var pubDateValue2 = Date.parse(b.pubDate); // Get milliseconds for date/time string
return pubDateValue1 - pubDateValue2;
// Sort all objects in the array using the comparison function
# Original Items Original Notes Sorted Items Sorted Notes