我在Facebook图形API中有以下数组。 我想通过comment_count,like_count,javascript中的时间对其进行排序。
[
{
"status_id": "1",
"message": "message1",
"comment_info": {
"comment_count": "1"
},
"like_info": {
"like_count": "0"
},
"time": "1380046653"
},
{
"status_id": "2",
"message": "message2",
"comment_info": {
"comment_count": "2"
},
"like_info": {
"like_count": "5"
},
"time": "1368109884"
}
] 我写了下面的函数,
function sortResults(prop, asc) {
statusString = statusString.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
console.log(statusString);
}
点击按钮
sortResults(['comment_info']['comment_count'], true);
但是它很受欢迎。
答案 0 :(得分:1)
您的函数没有考虑需要访问嵌套数组的深层属性的多维排序。 这是一个工作示例JSFIDLE link (click here)
var jSon = [{"status_id":"1","message":"message1","comment_info":{"comment_count":"1"},"like_info":{"like_count":"0"},"time":"1380046653"},{"status_id":"2","message":"message2","comment_info":{"comment_count":"2"},"like_info":{"like_count":"5"},"time":"1368109884"}];
// Function that sorts arr Array
// by prop (handling custom Fb cases)
// in dir direction (asc/desc)
function sortJson(arr, prop, dir) {
return arr.sort(function(a,b) {
var propA,propB;
if (prop == "comment_count") {
propA = a['comment_info']['comment_count'];
propB = b['comment_info']['comment_count'];
} else if (prop == "like_count") {
propA = a['like_info']['like_count'];
propB = b['like_info']['like_count'];
} else {
propA = a[prop];
propB = b[prop];
}
if (dir=='asc') {
return propA - propB;
} else {
return propB - propA;
}
});
}
console.log( sortJson(jSon, 'time', 'asc') );
console.log( sortJson(jSon, 'comment_count', 'asc') );
console.log( sortJson(jSon, 'like_count', 'desc').toString() );
答案 1 :(得分:0)
你可能需要来自native []的排序函数。
[]。排序(的compareFunction) 来自here的示例:
function compare(a, b) {
if (a is less than b by some ordering criterion)
return -1;
if (a is greater than b by the ordering criterion)
return 1;
// a must be equal to b
return 0;
}
答案 2 :(得分:0)
让我们说你的排序顺序就像你提到的那样:
var arr = [{"status_id":"1","message":"message1","comment_info":{"comment_count":"1"},"like_info":{"like_count":"0"},"time":"1380046653"},{"status_id":"2","message":"message2","comment_info":{"comment_count":"2"},"like_info":{"like_count":"5"},"time":"1368109884"}];
arr.sort(function (a, b) {
var countA = parseInt(a["comment_info"]["comment_count"]);
var countB = parseInt(b["comment_info"]["comment_count"]);
var likeCountA = parseInt(a["like_info"]["like_count"]);
var likeCountB = parseInt(b["like_info"]["like_count"]);
var timeA = a["time"];
var timeB = b["time"];
return ((countA - countB) || (likeCountA - likeCountB) || (timeA - timeB));
});