PDA

View Full Version : Array.sortDates ,Array.unique, and extended Array.indexOf



wm003
4 Mar 2008, 3:27 AM
//Sorts an Array that consists of date-objects only (Ext-specific)
Array.prototype.sortDates = function() {
return this.sort(function(a,b){
return parseInt(a.format("YmdHis"))-parseInt(b.format("YmdHis"));
});
};
The following was found at http://www.4umi.com/web/javascript/array.htm
(There are some more useful prototypes ...)



//override the existing indexOf to be able to look after a specific index and check vartypes
//extended with begin and strict attributes (backward compatible to current ext-indexOf function!)
Array.prototype.indexOf = function( o, b, s ) {
for( var i = +b || 0, len = this.length; i < len; i++) {
//check for objecttype to make this function work with date-objects also
if( this[i]===o || s && this[i]==o || Ext.isDate(o) && this[i].toString()==o.toString()) {
return i;
}
}
return -1;
};

// Array.unique( strict ) - Remove duplicate values
//based on new indexOf defined above
Array.prototype.unique = function(b) {
var a = [], i, len = this.length;
for(i=0; i<len; i++ ) {
if( a.indexOf( this[i], 0, b ) < 0 ) {
a.push( this[i] );
}
}
return a;
};

wm003
4 Mar 2008, 4:38 AM
Changed the indexOf routine a bit to make it work with Date Objects

wm003
2 May 2008, 8:09 AM
Needed to FIx the indexOf routine again to check for _real_ dateobjects....if you were going to use the above routine, you need to update, otherwise some important ext-features might not work correctly anymore

mystix
4 May 2008, 12:38 AM
to make Date sorting non-Ext specific, you could simply implement sortDates() using the Date object's built-in getTime() method


// Sorts an Array that consists of date-objects only
Array.prototype.sortDates = function() {
return this.sort(function(a, b) {
return a.getTime() - b.getTime();
});
};