Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 排序数组,使具有空值的项最后出现_Javascript_Arrays_Sorting - Fatal编程技术网

Javascript 排序数组,使具有空值的项最后出现

Javascript 排序数组,使具有空值的项最后出现,javascript,arrays,sorting,Javascript,Arrays,Sorting,我有以下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_

我有以下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的解决方案。

您可以像这样使用
sort()

var tweets=[{
“身体”:“RT废话废话废话”,
“图像”:“,
“屏幕名称”:“billsmith”,
“时间戳”:“2016-02-28 08:19:02”
}, {
“身体”:“RT废话废话废话”,
“图像”:http://www.image.com",
“屏幕名称”:“JoeBloggs”,
“时间戳”:“2016-06-28 07:37:40”
}]
tweets.sort(函数(a,b){
如果(b.图像长度){
返回1;
}否则{
返回-1;
}
})

console.log(tweets)
此建议仅将填充字符串排序到顶部,将空字符串排序到底部,而不进行任何其他排序

var tweets=[{body:“RT blah blah blah blah blah”,图像:,屏幕名称:“billsmith”,时间戳:“2016-02-28 08:19:02”},{body:“RT blah blah blah blah blah blah blah”,图像:http://www.image.com,屏幕名称:“JoeBloggs”,时间戳:“2016-06-28 07:37:40”});
tweets.sort(函数(a,b){
return!a.image-!b.image;
});
console.log(tweets)
var tweets=[{
“身体”:“RT废话废话废话”,
“图像”:“,
“屏幕名称”:“billsmith”,
“时间戳”:“2016-02-28 08:19:02”
},{
“身体”:“RT废话废话废话”,
“屏幕名称”:“billsmith”,
“时间戳”:“2016-02-28 08:19:02”
}, {
“身体”:“RT废话废话废话”,
“图像”:http://www.image.com",
“屏幕名称”:“JoeBloggs”,
“时间戳”:“2016-06-28 07:37:40”
}]
tweets.sort(函数(a,b){
return!a.image | | a.image==“”?1:-1;
})

log(tweets)
这是按图像url排序的,OP没有请求,所以可能不可取。Nenad Vracar的答案是更干净的IMHO。