4 回答
TA贡献1886条经验 获得超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);
TA贡献1786条经验 获得超11个赞
你快到了...只需在排序回调中稍作改动,就完成了::
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);
TA贡献1853条经验 获得超18个赞
你可以使用 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']);
输出将是
TA贡献1815条经验 获得超6个赞
尝试这个:
years.sort((c1, c2) => {
if (c1.name > c2.name) return -1;
if (c1.name < c2.name) return 1;
return 0;
});
添加回答
举报