json对象截取后三个数据,并按照时间的顺序进行倒叙排序。
var json = [{"sent_time":"08:29:09","dist":"北京"},{"sent_time":"07:28:55","dist":"上海"},{"sent_time":"08:32:09","dist":"天津"},{"sent_time":"06:29:15","dist":"广州"},{"sent_time":"06:15:24","dist":"深圳"}] var compare = function (prop) { return function (obj1, obj2) { var val1 = obj1[prop]; var val2 = obj2[prop]; if (!isNaN(Number(val1)) && !isNaN(Number(val2))) { val1 = Number(val1); val2 = Number(val2); } if (val1 < val2) { return 1; } else if (val1 > val2) { return -1; } else { return 0; } } } if(json.length>3){ var data = json.slice(json.length-3,json.slength).sort(compare("age")); }else { var data = json.sort(compare("age")); } console.log(data);
对json数据某一字段进行排序
var s = [{ "draggable": "true", "name": "58.237.119.223", "category": "源ip", "value": "1" }, { "draggable": "true", "name": "254.3.104.223", "category": "目的ip", "value": "3" }, { "draggable": "true", "name": "97.19.104.223", "category": "目的ip", "value": "2" }];
s.sort(function(a,b){ return a.value - b.value; });
截取前两个
s.slice(0,2);