Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1282 How do I sort an array of identical objects with more than one property within them, sorting the array on the values within any one of those properties?

irt.org | Knowledge Base | JavaScript | Object | Q1282 [ previous next ]

Q1282 How do I sort an array of identical objects with more than one property within them, sorting the array on the values within any one of those properties?

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>

Feedback on 'Q1282 How do I sort an array of identical objects with more than one property within them, sorting the array on the values within any one of those properties?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.