猿问

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

我有一个这样的数组


 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”方式我该怎么做最好的方法是什么


尚方宝剑之说
浏览 104回答 4
4回答

MM们

您可以使用localeCompareconst 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);

Qyouu

你快到了...只需在排序回调中稍作改动,就完成了::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);

慕容森

你可以使用 lodash_.sortByvar 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']);输出将是

红糖糍粑

尝试这个:years.sort((c1, c2) => {&nbsp; if (c1.name > c2.name) return -1;&nbsp; if (c1.name < c2.name) return 1;&nbsp; return 0;});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答