如何使用字符串类型对象的键值对对象数组进行排序

问题描述 投票:0回答:4

我有这样的数组

 let years =[
       {id: 3, name: "2016", age: "None"},
       {id: 1, name: "2017", age: "None"},
       {id: 2, name: "2015", age: "None"},
       {id: 5, name: "2018", age: "None"},
       {id: 3, name: "2018/2019", age: "None"}
       ]
       
years.sort((c1, c2) => {
        return c2.name - c1.name;
       });
       
console.log(years);       

我无法处理这种“ 2018/2017”方法,我该怎么办?这是最好的方法

javascript arrays sorting object
4个回答
2
投票

您可以使用localeCompare

const years = [
    { id: 3, name: '2016', age: 'None' },
    { id: 1, name: '2017', age: 'None' },
    { id: 2, name: '2015', age: 'None' },
    { id: 5, name: '2018', age: 'None' },
    { id: 3, name: '2018/2019', age: 'None' },
];

years.sort((c1, c2) => c2.name.localeCompare(c1.name));

console.log(years);

0
投票

尝试一下:

years.sort((c1, c2) => {
  if (c1.name > c2.name) return -1;
  if (c1.name < c2.name) return 1;
  return 0;
});

0
投票

您可以使用lodash _.sortBy

var years =
[{id: 5, name: "2018", age: "None"},
 {id: 3, name: "2018/2017", age: "None"},
 {id: 1, name: "2017", age: "None"},
 {id: 3, name: "2016", age: "None"},
 {id: 2, name: "2015", age: "None"}]

_.sortBy(years, ['name']);

输出为

enter image description here


0
投票

您快到了...在您的排序回调中做了一点改动就完成了:

let years = [
    { id: 3, name: '2016', age: 'None' },
    { id: 1, name: '2017', age: 'None' },
    { id: 2, name: '2015', age: 'None' },
    { id: 5, name: '2018', age: 'None' },
    { id: 3, name: '2018/2019', age: 'None' },
];
years.sort((c1, c2) => {
    var n1 = c1.name;
    var n2 = c2.name;
    if(n1 > n2){return -1;
    }else if(n2 > n1){ return 1;
}else{return 0;}
   });
console.log(years);
推荐问答
热门问答
最新问答