如何使用JavaScript对以下JSON字符串进行排序。
输入:
[{time:'1 hours ago'}, {time:'10 minutes ago'}, {time:'2 minutes ago'}]
输出:
[{time:'2 minutes ago'}, {time: '10 minutes ago'}, {time:'1 hours ago'}]
答案 0 :(得分:1)
这是一个粗略的样本。
var getVal = function(timeStr){
var arr = timeStr.split(" ");
var factor = 1;
switch(arr[1]){
case "minutes":factor = 1; break;
case "hours" :factor = 60; break;
case "days" :factor = 1440;break;
}
return parseInt(arr[0]) * factor;
}
var tgt = [{time:'2 minutes ago'}, {time: '10 minutes ago'}, {time:'1 hours ago'}];
tgt.sort(function(a,b){
return getVal(a.time) - getVal(b.time);
});
console.log(tgt);