JavaScript按几个月排序项目列表 [英] JavaScript sort items list by months

查看:73
本文介绍了JavaScript按几个月排序项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩js脚本。如何按月对列表项进行排序。最好的方法是什么?

I am playing with js scripts. How to sort items of list by months. What is the best way to do it?

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" } }
        ];


推荐答案

你可以通过列出所有的几个月的正确顺序,并根据它们对数组进行排序:

You can do it by having a list of all the months in the right order, and sorting your array based on them:

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按几个月排序项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆