排序键和键的值,键是月

时间:2018-05-28 18:37:30

标签: javascript arrays sorting

我有一个数组,其中键为月份,值为该月的总费用。

[May: 629, April: 300, March: 50]

我想根据密钥即月份来订购这个数组。 我想要的结果:

[ March: 50,  April: 300, May: 629]

我试图通过这样做来对键进行排序:

var months = ["January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"];

var sorted_keys = Object.keys(arr).sort(function(a,b){
  return months.indexOf(a)
           - months.indexOf(b);
});

我如何对整个数组进行排序?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

Try something like this:

var op3MembrosDisp = [];

var w = { id: 2, name: 'karen' };
op3MembrosDisp.push(w);

var w = { id: 1, name: 'Joseph' };
op3MembrosDisp.push(w);

op3MembrosDisp.sort(
            function (a, b) {
                var aId = a.name;
                var bId = b.name;
                return ((aId < bId) ? -1 : ((aId > bId) ? 1 : 0));
            }
        );

答案 1 :(得分:0)

Assuming your input is an array of String with a format like "month: expense", the idea is to extract the month from that entry, and sort that array based on month. Now to sort the array, we use the month map where each month is ranked.

var monthsHash = {
    "January": 1,
    "February": 2,
    "March": 3,
    "April": 4,
    "May": 5,
    "June": 6,
    "July": 7,
    "August": 8,
    "September": 9,
    "October": 10,
    "November": 11,
    "December": 12
};

var input = ["May: 629", "April: 300", "March: 50"]

input.sort(function (a, b) {
    var a_month = a.split(":")[0],
        b_month = b.split(":")[0],
        a_month_rank = monthsHash[a_month],
        b_month_rank = monthsHash[b_month];

    return a_month_rank - b_month_rank;
});

console.log(input);