JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Js对二维数组排序

2019. 11. 04    

Js对二维数组排序

d3_ascending = function(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
d3.descending = function(a, b) {
  return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
};

例子一;

let arr = [
  {name:"Dawson", totalScore:"197", Chinese:"100",math:"97"},
  {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"97"},
  {name:"LiLei", totalScore:"185", Chinese:"88", math:"97"},
  {name:"XiaoMing", totalScore:"193", Chinese:"96",math:"100"},
]


//降序
descending(property) {
  return function(obj1, obj2) {
    let value1 = obj1[property];
    let value2 = obj2[property];
    return value2 - value1;
  };
}
//双重降序
//比如 先按照父级排序 如果父级相等,则按照子级降序
ascending(property,tproperty) {
  return function(obj1, obj2) {
    let value1 = obj1[property];
    let value2 = obj2[property];
    if((value1 - value2)==0){
      let value3 = obj1[tproperty];
      let value4 = obj2[tproperty];
      return value3 - value4;
    }else{
      return value1 - value2;
    }
  };
},
//执行
arr = arr.sort(descending("totalScore"))

//结果:

[
  {name:"Dawson", totalScore:"197", Chinese:"100",math:"97"},
  {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"97"},
  {name:"XiaoMing", totalScore:"193", Chinese:"96",math:"100"},
  {name:"LiLei", totalScore:"185", Chinese:"88", math:"97"},
]

例子二;

let content = [
  {
    "id": "1",
    "stats": {
      "id": "1",
      "comment_count": 142
    }
  },
  {
    "id": "2",
    "stats": {
      "id": "2",
      "comment_count": 200
    }
  },
  {
    "id": "3",
    "stats": {
      "id": "3",
      "comment_count": 1242
    }
  },
  {
    "id": "4",
    "stats": {
      "id": "4",
      "comment_count": 46111
    }
  },
  {
    "id": "5",
    "stats": {
      "id": "5",
      "comment_count": 41422
    }
  }
]


//降序
descending(property) {
  return function(obj1, obj2) {
    var value1 = obj1.stats[property];
    var value2 = obj2.stats[property];
    return value2 - value1;
  };
}
//执行
arr = arr.sort(descending("comment_count"))

//结果
content = [
  {
    "id": "4",
    "stats": {
      "id": "4",
      "comment_count": 46111
    }
  },
  {
    "id": "5",
    "stats": {
      "id": "5",
      "comment_count": 41422
    }
  },
  {
    "id": "3",
    "stats": {
      "id": "3",
      "comment_count": 1242
    }
  },
  {
    "id": "2",
    "stats": {
      "id": "2",
      "comment_count": 200
    }
  },
  {
    "id": "1",
    "stats": {
      "id": "1",
      "comment_count": 142
    }
  }
]