Custom sorting of objects in js

1  // And return a comparison function that can be used to sort an array of objects containing that member 
2          var compareAsc = function (prop) {
 3              return  function (obj1, obj2) {
 4                  var val1 = obj1[prop];
 5                  var val2 = obj2[prop];
 6                  if (!isNaN(Number(val1)) && ! isNaN(Number(val2))) {
 7                      val1 = Number(val1);
 8                      val2 = Number(val2);
 9                  }
 10                  if ( val1 < val2) {
 11                      return -1;
12                 } else if (val1 > val2) {
13                     return 1;
14                 } else {
15                     return 0;
16                 }            
17             } 
18         }
19         var compareDesc = function (prop) {
20             return function (obj1, obj2) {
21                 var val1 = obj1[prop];
22                 var val2 = obj2[prop];
23                 if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
24                     val1 = Number(val1);
25                     val2 = Number(val2);
26                 }
27                 if (val1 > val2) {
28                     return -1;
29                 } else if (val1 < val2) {
30                     return 1;
31                 } else {
32                     return 0;
33                 }            
34             } 
35         }

Sorting in original js cannot satisfy:

arr.sort(sortNumber);
arr.sort(function (a, b) {
return b.name < a.name;
});

List of malls - points are arranged from high to low and from low to high:

 1 $scope.up=true;
 2         $scope.down = false;
 3         $scope.upDown = function(i) {
 4             $scope.up=!$scope.up;
 5             $scope.down=!$scope.down
 6             if($scope.up == true && $scope.down == false){
 7                 intData.sort(compareAsc("price"));
 8             }else if($scope.up == false && $scope.down == true){
 9                 intData.sort(compareDesc("price"));
10             }
11         };

html:

<a class="col col-50" ng-click="upDown()">{{'jifen.sortUp' | i18next}}   <i ng-class="{'ion-ios-arrow-thin-up':up,'ion-ios-arrow-thin-down':down }" class="icon "></i></a>

Reference: http://www.jb51.net/article/67458.htm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324466757&siteId=291194637