Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

javascript - Sort an array on month order

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],["March",40],["April",40],["May",50],["June",60]]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...