Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Non-destructive Sort And Reverse

DZone's Guide to

Non-destructive Sort And Reverse

·
Free Resource

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]
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}