js中排序问题总结

时间:2022-01-27 07:20:57

js的排序中通常使用到sort函数,可以用冒泡排序,插入排序,快速排序,希尔排序,系统方法等方法,本文结束后分享一个用着排序算法的链接,感兴趣可以了解了解。

1、常见的对一般数组进行排序,代码如下:

  var a =[ 1,3,123,41,5];

          //js sort 排序    a-b 从小到大排序,  b-a 从大到小排序
function sort(){
a.sort(function(a,b){
return a-b;
});
};
console.log(a);

2、对特殊数组的排序,代码如下:

  // 期望结果[张1广州,小张4广州,李2上海,小李3上海,赵5深圳,王7北京]
var arr = [
["张", "1:00", "广州"],
["小张", "4: 00", "广州"],
["王", "7: 00", "北京"],
["李", "2: 00", "上海"],
["小李", "3: 00", "上海"],
["赵", "5: 00", "深圳"]
]; var tmp = "广州,上海,深圳,北京";
arr.sort(function(a, b) {
var da = new Date("1111/1/1," + a[1].replace(/^\s*|\s*$/g, '') + ":0");
var db = new Date("1111/1/1," + b[1].replace(/^\s*|\s*$/g, '') + ":0");
var pa = tmp.indexOf(a[2]),
pb = tmp.indexOf(b[2]);
if (pa > pb) {
return 1;
} else if (pa < pb) {
return -1;
} else {
if (da > db) {
return 1;
} else if (da < db) {
return -1;
} else {
return 0;
}
}
});

3、对一个数组对象来排序,代码如下:

   // 按照对象属性来排序  希望返回结果:
/* {"name":"aa","age":21,"place":"cplace"},
{"name":"aa","age":21,"place":"eplace"},
{"name":"aa","age":22,"place":"aplace"},
{"name":"aa","age":22,"place":"cplace"},
{"name":"aa","age":22,"place":"dplace"},
{"name":"aa","age":23,"place":"dplace"},
{"name":"bb","age":21,"place":"eplace" },
{"name":"bb","age":22,"place":"vplace" },
{"name":"bb","age":24,"place":"fplace" },
{"name":"cc","age":12,"place":"aplace"},
{"name":"ee","age":29,"place":"fplace"},*/
var myArry = [{"name":"bb","age":22,"place":"vplace" },
{"name":"cc","age":12,"place":"cplace"},
{"name":"aa","age":21,"place":"cplace"},
{"name":"aa","age":23,"place":"dplace"},
{"name":"aa","age":21,"place":"eplace"},
{"name":"aa","age":22,"place":"aplace"},
{"name":"aa","age":22,"place":"cplace"},
{"name":"aa","age":22,"place":"dplace"}, {"name":"bb","age":24,"place":"fplace" },
{"name":"ee","age":29,"place":"fplace"},
{"name":"bb","age":21,"place":"eplace" }]
myArry.sort(function(a,b){
if(a.name< b.name){
return -1;
}else if(a.name > b.name) {
return 1;
}else {
if(a.age< b.age){
return -1;
}else if(a.age> b.age){
return 1;
}else {
if(a.name< b.name){
return -1;
}else if(a.age> b.age){
return 1;
}else{
return 0;
} }
}
})

4、对一个数组对象按照指定顺序排列,代码如下:

  var myArry = [{"name":"渭南","age":22,"place":"vplace" },
{"name":"商洛","age":12,"place":"cplace"},
{"name":"汉中","age":22,"place":"dplace"},
{"name":"西安","age":23,"place":"dplace"},
{"name":"延安","age":21,"place":"eplace"},
{"name":"榆林","age":22,"place":"aplace"},
{"name":"宝鸡","age":22,"place":"cplace"}, {"name":"铜川","age":24,"place":"fplace" },
{"name":"榆林","age":21,"place":"cplace"}];
var temp = "西安,汉中,渭南,商洛,延安,榆林,宝鸡,铜川";
myArry.sort(function(a,b){
var pa = temp.indexOf(a.name);
var pb = temp.indexOf(b.name);
if(pa< pb){
return -1;
}else if(pa > pb) {
return 1;
}else {return 0;
}
})

另外分享一个连接:http://www.cnblogs.com/idche/archive/2011/02/16/1956397.html 讲的是冒泡排序,插入排序,快速排序,希尔排序,系统方法等方法进行排序。