JS对Array进行自定制排序

时间:2021-08-30 23:38:03

JS对Array进行自定制排序,简单的做一个记录,代码如下所示:

        //Test function
function myFunction(){
var myArr = new Array();
var data1 = new Object();
data1.Name = "BBB";
data1.Age = 20;
var data2 = new Object();
data2.Name = "AAA";
data2.Age = 20;
myArr.push(data1);
myArr.push(data2);
myArr.sort(sortByName);
} //This will sort your array
function sortByName(a, b){
var aName = a.Name.toLowerCase();
var bName = b.Name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

....