js数组的多条件排序

使用js自带的sort来进行处理。

sort方法的解释说明:http://www.w3school.com.cn/js/jsref_sort.asp

<!-- 先按照city排好序,再按照home进行排序,最后按照size排序 -->
var data = [
	{"city": "四川", "home":"成都", "size": "1"},
	{"city": "广东", "home":"深圳", "size": "3"},
	{"city": "广东", "home":"广州", "size": "5"},
	{"city": "四川", "home":"自贡", "size": "2"},
	{"city": "广东", "home":"广州", "size": "2"}
	];
var dataSort=function(a,b){
  if (a["city"] === b["city"]) {
        if(a["home"] === b["home"]){
	  if (a["size"] > b["size"]) {
		  return 1;
	  } else{
		  return - 1;
	  }
	}else{
	  if (a["home"] > b["home"]) {
		  return 1;
	  } else {
		  return - 1;
	  }
	}
    } else {
        if (a["city"] > b["city"]) {
                return 1;
        } else {
                return - 1;
        }
    }
}
data.sort(dataSort);
console.log(data);

打印结果:

  

猜你喜欢

转载自www.cnblogs.com/zhaozhou/p/10761471.html
今日推荐