【问题标题】:Sort an array on month order按月顺序对数组进行排序
【发布时间】:2016-05-11 15:27:50
【问题描述】:

我想对这个数组进行排序,按照月份Jan, feb, march等等。 在前端使用 JavaScript

[[["February",17],["January",30],["March",40],["April",40],["May",50],["June",60]]]

【问题讨论】:

    标签: javascript


    【解决方案1】:

    sort() 与月订单映射对象一起使用

    var data = [
      ["June", 60],
      ["February", 17],
      ["January", 30],
      ["March", 40],
      ["April", 40],
      ["May", 50]
    ];
    // object which holds the order value of the month
    var monthNames = {
      "January": 1,
      "February": 2,
      "March": 3,
      "April": 4,
      "May": 5,
      "June": 6,
      "July": 7,
      "August": 8,
      "September": 9,
      "October": 10,
      "November": 11,
      "December": 12
    };
    
    // sort the data array
    data.sort(function(a, b) {
      // sort based on the value in the monthNames object
      return monthNames[a[0]] - monthNames[b[0]];
    });
    
    document.write('<pre>' + JSON.stringify(data, 0, 3) + '</pre>')

    【讨论】:

    • 非常感谢...它又好又干净
    • @NikitPatel : 很高兴为您提供帮助 :)
    • 可以简化为简单的月份数组和return monthNames.indexOf(a[0]) - monthNames.indexOf(b[0]);
    • @mplungjan ...我认为,虽然与属性访问器 indexOf 方法比较会更慢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    相关资源
    最近更新 更多