javascript - 如何使用 firebase 和 Node js 基于日期时间对数据进行排序

标签 javascript node.js

enter image description here

这是我当前的 json 响应。我想做的是根据时间对其进行排序。

router.get('/getmessage/:uuid',function(req, res){
    chatID = req.params.uuid;

    var chat = database.ref('chats/'+ chatID);
    id = _.split(chatID, '_', 2);
    chat.once('value', function(snapshot){
        dataSet = [];

        snapshot.forEach(function(childsnapshot){

            dataSet.push({
                child: childsnapshot
            })
        })
        newDataSet = dataSet.sort(function(a,b){

            return a.child.val().time - b.child.val().time;
        })
        res.json(newDataSet);
    })
});

这是我的脚本。我尝试使用 .sort 但是当我尝试 console.log(a.child.val().time - b.child.val().time) 它返回 NaN 但我仍然得到了当前结果.. 这是我想要得到的结果。 enter image description here

最佳答案

您可以将 array#sortstring#localeCompare 一起使用。

var data = [{child:{time:'2018-02-21 16:41:30'}}, {child:{time:'2018-02-21 16:30:21'}}];
data.sort((a,b) => a.child.time.localeCompare(b.child.time));
console.log(data);

关于javascript - 如何使用 firebase 和 Node js 基于日期时间对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901708/

相关文章:

javascript - Fabric .js : clip everything but overlay image

javascript - 为什么即使我将值插入其中,空数组仍然为空?

node.js - Brew 安装后 Node 使用错误版本

javascript - 不使用选择框创建下拉列表

java - HTML 页面作为 AJAX 响应?

javascript - 模式在 Ember.js 应用程序中不起作用

node.js - 使用 Nodejs 实时抓取聊天记录

javascript - 使用 javascript 我需要替换文档中的匹配字符串

node.js - Amazon S3 EPIPE 错误

javascript - 函数附加的全局数组在其他地方显示为零长度