Sort an array on month order

前端 未结 1 1109
鱼传尺愫
鱼传尺愫 2020-12-04 01:31

I want to sort this array, According to the month Jan, feb, march and so on. using JavaScript on front-end

[[[\"February\",17],[\"January\",30],         


        
相关标签:
1条回答
  • 2020-12-04 01:48

    Use sort() with a month order mapping object

    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>')

    0 讨论(0)
提交回复
热议问题