JS Sort


JS sort() function is a method of Array Object.

Sort a number array:

var arr = new Array(1,2,3,2,5,11,14);
arr.sort(); //arr now is [1,2,2,3,5,11,14]

The default is ascending sort.

Sort a string array:

var arr = new Array("lin","Mike","John","aly");
arr.sort(); //arr now is "John","Mike","aly","lin"

The default is ascending sort, uppercase before lowercase.

Sort a string array descendingly:

var arr = new Array("lin","Mike","John","aly");
arr.sort();
arr.reverse(); //"lin","aly","Mike","John"


Similarly, sort a number array descendingly:

var arr = new Array(1,2,3,2,5,11,14);
arr.sort();
arr.reverse(); //arr now is [14,11,5,3,2,2,1]


Sort a number array descendingly another way:

var arr = new Array(1,2,3,2,5,11,14);
arr.sort(function(x,y) {return y-x;});
//[14,11,5,3,2,2,1]


Sort an array of Objects, for example JSON:

var branches = [{
	"city":"New York",
	"employee":20,
	"offices":3,
	"director":"Jack Mayer"
},{
	"city":"Seattle",
	"employee":5,
	"offices":1,
	"director":"Jenniffer Larson"
},{
	"city":"Houston",
	"employee":12,
	"offices":2,
	"director":"Richard Trostle"
}];
//sort by emplyee ascendingly
function employeeascend(x,y)
{
	return x.employee > y.employee;
}
//sort by emplyee decendingly
function employeeascend(x,y)
{
	return x.employee < y.employee;
}
branches.sort(employeeascend);

endmemo.com © 2024  | Terms of Use | Privacy | Home