我正在玩js脚本。如何按月对列表项进行排序。最好的方法是什么?
var dataCollection = [
{ values: { Month: { displayValue: "August" }, Sum: "10" } },
{ values: { Month: { displayValue: "February" }, Sum: "25" } },
{ values: { Month: { displayValue: "July" }, Sum: "35" } }
];
我希望得到
dataCollection = [
{ values: { Month: { displayValue: "February" }, Sum: "25" } },
{ values: { Month: { displayValue: "July" }, Sum: "35" } },
{ values: { Month: { displayValue: "August" }, Sum: "10" } }
];
答案 0 :(得分:11)
您可以通过按正确的顺序列出所有月份的列表,并根据它们对数组进行排序来实现:
var dataCollection = [
{ values: { Month: { displayValue: "August" }, Sum: "10" } },
{ values: { Month: { displayValue: "February" }, Sum: "25" } },
{ values: { Month: { displayValue: "July" }, Sum: "35" } }
];
sortByMonth(dataCollection);
console.log(dataCollection);
function sortByMonth(arr) {
var months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
arr.sort(function(a, b){
return months.indexOf(a.values.Month.displayValue)
- months.indexOf(b.values.Month.displayValue);
});
}
答案 1 :(得分:0)
在上面@blex的回答(被接受的问题)上功不可没,我想扩展一下以确保排序方法...得到了增强。
// 1. Expect an array of Months, long or short format:
// ["Jan", "Mar", "Feb"] or ["January", "march", "FEBRUARY"]
// 2. Support optional reverse sorting.
// 3. Ensure SAFE sorting (does not modify the original array).
function sortByMonthName(monthNames, isReverse = false) {
const referenceMonthNames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
const directionFactor = isReverse ? -1 : 1;
const comparator = (a, b) => {
if (!a && !b) return 0;
if (!a && b) return -1 * directionFactor;
if (a && !b) return 1 * directionFactor;
const comparableA = a.toLowerCase().substring(0, 3);
const comparableB = b.toLowerCase().substring(0, 3);
const comparisonResult = referenceMonthNames.indexOf(comparableA) - referenceMonthNames.indexOf(comparableB);
return comparisonResult * directionFactor;
};
const safeCopyMonthNames = [...monthNames];
safeCopyMonthNames.sort(comparator);
return safeCopyMonthNames;
}
// Examples:
const dataset = ["Mar", "January", "DECEMBER", "february"];
const test1 = sortByMonthName(dataset);
const test2 = sortByMonthName(dataset, true);