You are here: irt.org | FAQ | JavaScript | Object | Q1282 [ previous next ]
Try the following:
<script language="JavaScript"><!-- function myObject(day,month,year,text,number) { this.day = day; this.month = month; this.year = year; this.text = text; this.number = number; } function setObject(day,month,year,text,number) { myObjectArray[objectArrayIndex++] = new myObject(day,month,year,text,number); } var objectArrayIndex = 0; var myObjectArray = new Array(); setObject(4,11,97,"abc",5); setObject(3,10,1996,"123",55); setObject(2,9,1995,"122",123); setObject(1,12,1998,"124",24); function compareDay(a,b) { return a.day - b.day; } function compareMonth(a,b) { return a.month - b.month; } function compareYear(a,b) { return a.year - b.year; } function compareText(a,b) { return a.text - b.text; } function compareNumber(a,b) { return a.number - b.number; } function showObjectArray(text,object,length) { document.write(text + ': '); for (var i=0; i<length; i++) { document.write('<br>' + object[i].day + ' '); document.write(object[i].month + ' '); document.write(object[i].year + ' '); document.write(object[i].text + ' '); document.write(object[i].number); } document.write('<br><br>'); } //var myArray = new Array(333,5,44,2222,11111); //var myArrayLength = 5; showObjectArray('Unsorted',myObjectArray,objectArrayIndex); myObjectArray.sort(compareDay); showObjectArray('Sorted by Day',myObjectArray,objectArrayIndex); myObjectArray.sort(compareMonth); showObjectArray('Sorted by Month',myObjectArray,objectArrayIndex); myObjectArray.sort(compareYear); showObjectArray('Sorted by Year',myObjectArray,objectArrayIndex); myObjectArray.sort(compareText); showObjectArray('Sorted by Text',myObjectArray,objectArrayIndex); myObjectArray.sort(compareNumber); showObjectArray('Sorted by Number',myObjectArray,objectArrayIndex); //--></script>