我有一个这样组织的数组。
const array = [
{
Year: 2018,
Month: 'Dec'
},
{
Year: 2017,
Month: 'Apr'
},
{
Year: 2018,
Month: 'Mar'
},
{
Year: 2018,
Month: 'Oct'
},
{
Year: 2017,
Month: 'Jan'
},
{
Year: 2018,
Month: 'Apr'
}
]
我已经成功地按年或按月组织了数据,但每次我尝试同时按这两种方式组织数据时,最后组织数据的那个将取代之前的所有数据。我理解它为什么这样做,但似乎无法找到解决方法。
const sortedByYear = array.sort((a, b) => a.Year - b.Year);
非常简单地按年份排序。
const sorted = sortedByYear.sort((a, b) => Months.indexOf(a.Month) - Months.indexOf(b.Month));
按月排序。
我尝试在月份检查器中添加某种检查器,如果年份匹配则求助,但这并没有解决如何排序的问题。
最佳答案
您必须将两个 测试放在您的sort
函数中:
const input = [
{
Year: 2018,
Month: 'Dec'
},
{
Year: 2017,
Month: 'Apr'
},
{
Year: 2018,
Month: 'Mar'
},
{
Year: 2018,
Month: 'Oct'
},
{
Year: 2017,
Month: 'Jan'
},
{
Year: 2018,
Month: 'Apr'
}
];
const Months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
input.sort((a, b) => {
if (a.Year !== b.Year) return a.Year - b.Year;
return Months.indexOf(a.Month) - Months.indexOf(b.Month)
});
console.log(input);
关于javascript - 如何在 Javascript ES6 中按年和月排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50124701/