DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Non-destructive Sort And Reverse

09.19.2005
| 9747 views |
  • submit to reddit
        
Array.prototype.clone = function(){
	return Array.apply(null,this)
};
Array.prototype.sortIt    = Array.prototype.sort;
Array.prototype.reverseIt = Array.prototype.reverse;
Array.prototype.sort = function(){
	var tmp = this.clone();
	return tmp.sortIt.apply(tmp,arguments)
}
Array.prototype.reverse = function(){
	var tmp = this.clone();
	return tmp.reverseIt.apply(tmp,arguments)
}

* before

var a = [5,4,3,2,1];
var b = a.sort();
alert(a); // [1,2,3,4,5]
alert(b); // [1,2,3,4,5]

var a = [1,2,3,4,5];
var b = a.reverse();
alert(a); // [5,4,3,2,1]
alert(b); // [5,4,3,2,1]


* after

var a = [5,4,3,2,1];
var b = a.sort();
alert(a); // [5,4,3,2,1]
alert(b); // [1,2,3,4,5]
a.sortIt();
alert(a); // [1,2,3,4,5]

var a = [1,2,3,4,5];
var b = a.reverse();
alert(a); // [1,2,3,4,5]
alert(b); // [5,4,3,2,1]
a.reverseIt();
alert(a); // [5,4,3,2,1]