1】冒泡法排列
//Implementing a simple bubble sort:Array.prototype.sort = function () { var tmp; for(var i=0;i<this.length;i++) { for(var j=0;j<this.length;j++) { if(this[i]<this[j]) { tmp = this[i]; this[i] = this[j]; this[j] = tmp; } } } }
2】根据一个属性进行排列
//Implementing a simple sort by property:
Array.prototype.sortByProperty = function (propertyName, sort) { if (isDefined(propertyName) ) { propertyName = '.' + propertyName; } // Default sort Ascending var tmp; for(var i=0;i<this.length;i++) { for(var j=0;j<this.length;j++) { if(eval('this[i]' + propertyName) < eval('this[j]' + propertyName)) { tmp = this[i]; this[i] = this[j]; this[j] = tmp; } } } if(isDefined(sort) && areEqual(sort, 'DESC')) { this.reverse(); } }
以下的例子根据属性position 和 label 进行排序
var self = this;
self.orderByPositionAndLabel = function (input) {
var tmp; var inputArray = input; for(var i=0;i<inputArray.length;i++) { for(var j=0;j<inputArray.length;j++) { if(inputArray[i].Position > inputArray[j].Position) { tmp = inputArray[i]; inputArray[i] = inputArray[j]; inputArray[j] = tmp; }else if(inputArray[i].Position == inputArray[j].Position){ if(inputArray[i].label > inputArray[j].label) { tmp = inputArray[i]; inputArray[i] = inputArray[j]; inputArray[j] = tmp; } } } } return inputArray.reverse(); }