我有以下Tweet数组:
tweets: [{
"body": "RT blah blah blah",
"image": "",
"screen_name": "billsmith",
"timestamp": "2016-02-28 08:19:02"
}, {
"body": "RT blah blah blah",
"image": "http://www.image.com",
"screen_name": "JoeBloggs_",
"timestamp": "2016-06-28 07:37:40"
}]
如何通过图片排序以便首先显示包含图片的推文?所以基本上我希望最后出现"image": ""
的推文。
我已尝试以下功能对商品进行重新排序,但它不起作用:
tweets.sort(function(a, b) {
return a.image - b.image;
});
任何想法都非常感激。我很高兴使用使用纯JavaScript或lodash的解决方案。
答案 0 :(得分:2)
您可以像这样使用sort()
。
var tweets = [{
"body": "RT blah blah blah",
"image": "",
"screen_name": "billsmith",
"timestamp": "2016-02-28 08:19:02"
}, {
"body": "RT blah blah blah",
"image": "http://www.image.com",
"screen_name": "JoeBloggs_",
"timestamp": "2016-06-28 07:37:40"
}]
tweets.sort(function(a, b) {
if (b.image.length) {
return 1;
} else {
return -1;
}
})
console.log(tweets)

答案 1 :(得分:0)
此提案仅将填充的字符串排序到顶部,将空字符串排序到底部,而不进行任何其他排序。
var tweets = [{ body: "RT blah blah blah", image: "", screen_name: "billsmith", timestamp: "2016-02-28 08:19:02" }, { body: "RT blah blah blah", image: "http://www.image.com", screen_name: "JoeBloggs_", timestamp: "2016-06-28 07:37:40" }];
tweets.sort(function(a, b) {
return !a.image - !b.image;
});
console.log(tweets);
答案 2 :(得分:0)
var tweets = [{
"body": "RT blah blah blah",
"image": "",
"screen_name": "billsmith",
"timestamp": "2016-02-28 08:19:02"
},{
"body": "RT blah blah blah",
"screen_name": "billsmith",
"timestamp": "2016-02-28 08:19:02"
}, {
"body": "RT blah blah blah",
"image": "http://www.image.com",
"screen_name": "JoeBloggs_",
"timestamp": "2016-06-28 07:37:40"
}]
tweets.sort(function(a, b) {
return !a.image || a.image === "" ? 1 : -1;
})
console.log(tweets)