有条件地按两个属性排序

时间:2018-06-10 07:27:17

标签: javascript arrays underscore.js lodash

考虑以下场景,我必须按名称和分数对学生列表进行排序。

[
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 }
]

我想由得分最高的学生对列表进行排序,但如果两个或更多学生的得分相同,那么我想按字母顺序对这些学生进行排序。对于上述情况,结果应如下所示:

[
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 }
]

我怎样才能做到这一点?我可以使用任何lodash函数,还是纯JavaScript可以使用?

4 个答案:

答案 0 :(得分:5)

不需要库,只需比较score,如果结果为0,则比较名称:

const arr=[{name:'Max',score:94},{name:'Jerome',score:86},{name:'Susan',score:86},{name:'Abel',score:86},{name:'Kevin',score:86}]

console.log(
  arr.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name))
);

答案 1 :(得分:1)

尝试以下方法:

var arr = [
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 }
];
arr.sort((a,b)=>{
 return (b.score - a.score) || a.name.localeCompare(b.name);
});
console.log(arr);

答案 2 :(得分:1)

您可以按_.sortBy排序,并为订单列出属性和其他属性。

var array = [{ name: 'Max', score: 94 }, { name: 'Jerome', score: 86 }, { name: 'Susan', score: 86 }, { name: 'Abel', score: 86 }, { name: 'Kevin', score: 86 }];

console.log(_.sortBy(array, ['score', 'name'], ['desc', 'asc']))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

答案 3 :(得分:1)

首先按分数对数组进行排序,如果两个分数相等,则按名称对其进行排序。请考虑以下代码:

&#13;
&#13;
let obj = [
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 }
];

obj.sort((a,b) => {
  if(b.score - a.score === 0){
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
  }
  else{
     return b.score - a.score;
  }
});

console.log(obj);
&#13;
&#13;
&#13;