2 回答

TA贡献1946条经验 获得超3个赞
您需要提供自定义比较器函数.sort以使用月份和年份进行排序。
const events = [
{
year: "2019",
month: "June",
title: "title",
desc: "desc"
},
{
year: "2019",
month: "June",
title: "title",
desc: "desc"
},
{
year: "2019",
month: "July",
title: "title",
desc: "desc"
},
{
year: "2018",
month: "June",
title: "title",
desc: "desc"
},
{
year: "2018",
month: "March",
title: "title",
desc: "desc"
},
{
year: "2018",
month: "March",
title: "title",
desc: "desc"
}
];
// Custom comparator function
function sortByMonthYear(a, b) {
const keyA = `${a.month} ${a.year}`;
const keyB = `${b.month} ${b.year}`;
if (keyA.localeCompare(keyB)) {
return -1;
}
else if (keyA === keyB) {
return 0;
}
return 1;
}
const grouping = events.sort(sortByMonthYear);
console.log(grouping);
更新:
您还可以使用 Array#prototype#reduce
const events = [{
year: "2019",
month: "June",
title: "title",
desc: "desc"
},
{
year: "2019",
month: "June",
title: "title",
desc: "desc"
},
{
year: "2019",
month: "July",
title: "title",
desc: "desc"
},
{
year: "2018",
month: "June",
title: "title",
desc: "desc"
},
{
year: "2018",
month: "March",
title: "title",
desc: "desc"
},
{
year: "2018",
month: "March",
title: "title",
desc: "desc"
}
];
const grouping = events.reduce((acc, curr) => {
const key = `${curr.month} ${curr.year}`;
if (!acc[key]) {
acc[key] = [curr];
} else {
acc[key].push(curr);
}
return acc;
}, {});
console.log(grouping);
添加回答
举报