智慧大石
您需要提供自定义比较器函数.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 functionfunction 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#reduceconst 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);