Javascript Sorting - Example 6

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 = {item: 5, note: "aaa"};

var testObject2 = {item: 4, note: "bbb"};

var testObject3 = {item: 3, note: "ccc"};

var testObject4 = {item: 2, note: "ddd"};

var testObject5 = {item: 1, note: "eee"};

// 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 item element in each object

function compareItems(a, b) {

return a.item - b.item;

}

// Sort all objects in the array using the comparison function

testArray.sort(compareItems);

# Original Items Original Notes Sorted Items Sorted Notes
1
2
3
4
5