months = ['Apr','Jan','Jul','Jun']
values = ['2','4','10','1']
如何按字母顺序对它们进行排序,但如下所示进行自定义,以便排序的数组应为:
sMonths = ['Jan','Apr','Jun','Jul']
sValues = ['4','2','1','10']
我猜它应该用map方法完成?我在这里查了一下:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
但我真的不明白该怎么做。
答案 0 :(得分:2)
将月份和值组合到一个数组中,对其进行排序,然后提取月份和值。
System.dll
答案 1 :(得分:-1)
您最好将月份存储为ID(1-> 12),最后将其转换为月份名称,但Andy E回复会在Sort day/month array in Javascript上填写您的需求
(function () {
// Set up our variables, 2 date objects and a map of month names/numbers
var ad = new Date(),
bd = new Date(),
months = {
Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov:10, Dec:12
};
MyArray.sort(function (a,b) {
// Split the text into [ date, month ]
var as = a.split(' '),
bs = b.split(' ');
// Set the Date() objects to the dates of the items
ad.setDate(as[0]);
ad.setMonth(months[as[1]]);
bd.setDate(bs[0]);
bd.setMonth(months[bs[1]]);
/* A math operation converts a Date object to a number, so
it's enough to just return date1 - date2 */
return ad - bd;
});
})();
//-> ["09 Jun", "13 Jun", "30 Jun", "13 Aug", "25 Aug"]