gpt4 book ai didi

JavaScript 按月对项目列表进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 04:53:50 26 4
gpt4 key购买 nike

我正在玩 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" } }
];

最佳答案

您可以按照正确的顺序列出所有月份,并根据它们对数组进行排序:

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);
});
}

关于JavaScript 按月对项目列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37349331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com