我有一系列带有月份的对象,我想按特定的顺序对它们进行排序,例如会计年度格式,我该怎么做?
(12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:{subscribedCustomers: 1, req_count: 1, revenue: 1532.82, getMonth: "April", totalComp: 1}
1:{subscribedCustomers: 0, req_count: 0, revenue: null, getMonth: "June", totalComp: 0}
2:{subscribedCustomers: 1, req_count: 1, revenue: 2948.82, getMonth: "May", totalComp: 1}
3:{getMonth: "July", totalComp: 0}
4:{getMonth: "August", totalComp: 0}
5:{getMonth: "September", totalComp: 0}
6:{getMonth: "October", totalComp: 0}
7:{getMonth: "November", totalComp: 0}
8:{getMonth: "December", totalComp: 0}
9:{getMonth: "January", totalComp: 0}
10:{getMonth: "February", totalComp: 0}
11:{getMonth: "March", totalComp: 0}
如何使用以下格式将其分类为月数
[ '四月', '可以', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月', '一月', '二月', '三月'];
答案 0 :(得分:3)
不是性能最高的版本,但应该这么做
const refArray = [ 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February', 'March'];
yourArray.sort((a,b) => { return refArray.indexOf(a.getMonth) - refArray.indexOf(b.getMonth)});
答案 1 :(得分:1)
您可以创建一个将月份映射到数字的对象,然后使用sort函数根据该对象的值对数组进行排序:
let data = [{subscribedCustomers: 1, req_count: 1, revenue: 1532.82, getMonth: "April", totalComp: 1},{subscribedCustomers: 0, req_count: 0, revenue: null, getMonth: "June", totalComp: 0},{subscribedCustomers: 1, req_count: 1, revenue: 2948.82, getMonth: "May", totalComp: 1},{getMonth: "July", totalComp: 0},{getMonth: "August", totalComp: 0},{getMonth: "September", totalComp: 0},{getMonth: "October", totalComp: 0},{getMonth: "November", totalComp: 0},{getMonth: "December", totalComp: 0},{getMonth: "January", totalComp: 0},{getMonth: "February", totalComp: 0},{getMonth: "March", totalComp: 0}];
const months = {"January": 1,"February": 2,"March": 3,"April": 4,"May": 5,"June": 6,"July": 7,"August": 8,"September": 9,"October": 10,"November": 11,"December": 12};
data.sort(function(a, b) {
return months[a.getMonth] - months[b.getMonth];
});
console.log(data)