mongoDB方法中没有提供汉字排序的功能,除非必须存汉字对应的ascii码,才能需要排序,但这样做又使数据库增加负担。最好的做法就是,数据库只存名称,前端获取到值之后,自己进行排序,这样就能提高性能,又能做到用户需求。
比如前端获得后台返回值:
"data2":["全场广告商户1","全场广告商户2","二号餐厅","三号咖啡","jhct","xiong","huhu1","绿茶餐厅","江南厨子","新月饭店","鑫益达","bhct","全场广告商户3","柳柳3","商户后台","全场广告商户4","测试","测试2","星巴克","猫屎咖啡","维拉度假别墅"]
代码实现:
$scope.getParkingNameList = data.data2; $scope.getParkingNameList = $scope.getParkingNameList.sort( function compareFunction(param1,param2) { return param1.localeCompare(param2); } );
排序之后:
["测试", "测试2", "二号餐厅", "江南厨子", "柳柳3", "绿茶餐厅", "猫屎咖啡", "全场广告商户1", "全场广告商户2", "全场广告商户3", "全场广告商户4", "三号咖啡", "商户后台", "维拉度假别墅", "新月饭店", "鑫益达", "星巴克", "bhct", "huhu1", "jhct", "xiong"]
比如前端获得后台返回值:
"data":[
{"parkingName":"小猫停车场","parkId":"99999888881474167822"},{"parkingName":"软件产业基地停车场","parkId":"0755000021433988491"},{"parkingName":"已审核停车场17","parkId":"99999999991474183853"
},
{"parkingName":"上川停车场","parkId":"11111222221474251256"},{"parkingName":"冰天雪地","parkId":"44444444441474266013"},{"parkingName":"冬天停车场","parkId":"55555555551474268580"
},
{"parkingName":"无敌停车场","parkId":"66666666661474265947"},{"parkingName":"花都停车场","parkId":"10732170901477292809"},{"parkingName":"熊猫国际软件园","parkId":"12345123451478226975"},
{"parkingName":"小猫猫","parkId":"78945612301479432508"},{"parkingName":"后台2","parkId":"18681498421480595335"},{"parkingName":"旧版测试停车场","parkId":"18712345671481190728"
},
{"parkingName":"测试停车场","parkId":"88888888881481708747"},{"parkingName":"无敌加油站321","parkId":"158273559891482455244"},{"parkingName":"young加油站1","parkId":"1234561482739920"}]
代码实现:
function compare(key){ return function (obj1,obj2){ var val1= obj1[key]; var val2= obj2[key]; return val1.localeCompare(val2); } }; $scope.openMonthCardList=data.data.sort(compare("parkingName"));
这是利用 JavaScript localeCompare() 的方法,localeCompare() 方法提供的比较字符串的方法,考虑了默认的本地排序规则。ECMAscript 标准并没有规定如何进行本地特定的比较操作,它只规定该函数采用底层操作系统提供的排序规则。