我有一个这种格式的数组。我需要将其降序排序:
[{
"9-Sep" : 6
}, {
"8-Sep" : 11
}, {
"7-Sep" : 4
}, {
"6-Sep" : 11
}, {
"5-Sep" : 16
}, {
"4-Sep" : 14
}, {
"3-Sep" : 3
}, {
"2-Sep" : 11
}, {
"15-Sep" : 28
}, {
"14-Sep" : 6
}, {
"13-Sep" : 8
}, {
"12-Sep" : 15
}, {
"11-Sep" : 24
}, {
"10-Sep" : 19
}];
我正在使用此函数,但仅当值不存在时才进行排序。
function myname() {
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
};
json.sort(function (a,b) {
var as = a.split('-'),
bs = b.split('-');
ad.setDate(as[0]);
ad.setMonth(months[as[1]]);
bd.setDate(bs[0]);
bd.setMonth(months[bs[1]]);
return ad - bd;
});
};
如何用值对上面的数组进行排序?
最佳答案
正如其他人提到的,您可能必须将数据提取为不同的格式才能对其进行排序:
var newArray = [];
//Extract array of transformed objects
for(var i = 0; i < json.length; i++) {
var element = json[i];
for(var key in element) {
if(element.hasOwnProperty(key)) {
newArray.push({ date: key, val: element[key]})
break;
}
}
}
//Sort transformed array
newArray.sort(function(a,b) {
var as = a.date.split('-'),
bs = b.date.split('-');
ad.setDate(as[0]);
ad.setMonth(months[as[1]]);
bd.setDate(bs[0]);
bd.setMonth(months[bs[1]]);
return ad - bd;
});
//Transform back to old format
for(var i = 0; i < newArray.length; i++) {
var x = {};
x[newArray[i].date] = newArray[i].val;
json[i] = x;
}
关于javascript - 如何对包含日期和值的数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18842332/