我有这种格式的数组。我需要按顺序排序:
[{
"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;
});
};
如何使用值对上面的数组进行排序?
答案 0 :(得分:3)
正如其他人所提到的,您可能必须将数据提取为不同的格式才能对其进行排序:
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;
}
答案 1 :(得分:2)
下面的代码工作正常,并做你真正想要的。
<script>
records = [{ "21-Feb": "IndPak" }, { "12-Oct": "AusSA" }, { "9-Sep": "WINZD" }, { "1-Jun": "NZDSL" }];
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
};
records = records.sort(function (d1, d2) {
var date1 = new Date(), date2 = new Date()
for (var prop in d1) {
if (d1.hasOwnProperty(prop)) {
day = prop.split("-")[0];
month = prop.split("-")[1];
date1.setDate(parseInt(day));
date1.setMonth(parseInt(months[month]));
}
}
for (var prop in d2) {
if (d2.hasOwnProperty(prop)) {
day = prop.split("-")[0];
month = prop.split("-")[1];
date2.setDate(parseInt(day));
date2.setMonth(parseInt(months[month]));
}
}
return date1 - date2; // Ascending
//return date2 - date1; // Descending
});
</script>