如何对javascript数组排序

如何对javascript数组排序,javascript,Javascript,我想按时间戳对数组排序,但得到未排序的错误 var userValue = { timestamp, username, token, userid, message }; userArray.push(userValue); 这是我得到的数组 我想要基于时间戳对数组进行排序以下代码根据时间戳的数值进行排序。它忽略跳过数组条目,并在必要时执行时间戳的字符串到数字的转换。它假

我想按时间戳对数组排序,但得到未排序的错误

var userValue = {
       timestamp,
       username,
       token,
       userid,
       message                      
   };
userArray.push(userValue);
这是我得到的数组


我想要基于时间戳对数组进行排序

以下代码根据时间戳的数值进行排序。它忽略跳过数组条目,并在必要时执行时间戳的字符串到数字的转换。它假设除了“string”和“number”之外,timstamps不属于其他数据类型

userArray.filter ( px_item => {
    return (px_item !== undefined);
})
.map ( px_item => {
    if (typeof px_item === "string") {
        return parseInt(px_item);
    } else {
        return px_item;
    }
})
.sort(function(a, b) {
    if (typeof a === "undefined") {
        return -1;
    } else {
        if (typeof b === "undefined") {
            return 1;
        } else {
            return Math.sign ( a['timestamp'] - b['timestamp'] );
        }
    }
});
原始代码的排序函数错误。这个函数实际上是一个比较函数,用于确定两个元素的相对顺序(在给定的用例中是数组条目)。顺序表示为数值
-1
a
)、
0
a=b
)和
1
a>b
)中的一个(事实上,为了正确处理比较结果,只要结果有正确的符号就足够了,因此可以消除
数学符号
).

此代码

userArray[childDatamsg.timestamp] = userValue;
时间戳
索引处添加对象。这就是为什么您有一个长度为1563533788的数组!相反,
userValue
对象推送到
userArray

userArray.push(userValue);
现在,它将具有
0
中的索引

然后可以按如下方式对数组进行排序:

userArray.sort((a, b) => a.timestamp - b.timestamp)

除非我错过了你有的东西?您想要升序还是降序?您可以将数组本身添加到您的问题中吗?我想要降序您为什么要执行
userArray[childDatamsg.timestamp]
?您的阵列现在的长度为15亿。使用
userArray.push(userValue)
我已经使用userArray.push(userValue)更新了代码,但是得到了2个结果???@coder\B:它与控制台中的
[,,,,,{timestamp:“4”},,,,,{timestamp:1}]
一起工作,该控制台被构造为原始数据的精简模拟。如果你能分享你的数据,我很乐意去看看这个问题。@coder_B对于初学者来说,哪种方式不起作用?它会抛出错误吗?我让它工作,数组在firebase代码之外不工作,所以我把代码放在firebase代码里面,所以它给了我正确的结果
userArray.sort((a, b) => a.timestamp - b.timestamp)