您正在处理聊天应用程序,我想对新邮件进行排序,并根据时间保留历史记录顺序。
例如,我在这样的数组中有聊天消息
[{"user":"a", "msg":"Hi ", "msg_count":1, "unix_time":"1474476800000"}
{"user":"b", "msg":"Hi ", "msg_count":1, "unix_time":"1478776800000"}
{"user":"c", "msg":"Hi ", "msg_count":5, "unix_time":"1479276800000"}
{"user":"d", "msg":"Hi ", "msg_count":1, "unix_time":"1478416800000"}
{"user":"e", "msg":"Hi ", "msg_count":3, "unix_time":"1478476800000"}]
我如何使用" msg_count"对它们进行排序?键,其中所有更大的值应该在顶部,但其余的对象应该使用" unix_time"键。
答案 0 :(得分:1)
使用Array#sort
方法和自定义比较功能。
var data=[{"user":"a", "msg":"Hi ", "msg_count":1, "unix_time":"1474476800000"},
{"user":"b", "msg":"Hi ", "msg_count":1, "unix_time":"1478776800000"},
{"user":"c", "msg":"Hi ", "msg_count":5, "unix_time":"1479276800000"},
{"user":"d", "msg":"Hi ", "msg_count":1, "unix_time":"1478416800000"},
{"user":"e", "msg":"Hi ", "msg_count":3, "unix_time":"1478476800000"}];
data.sort(function(a, b) {
// return the difference of `msg_count` property to sort based on them
// if they are equal then sort based on unix_time prop
return b.msg_count - a.msg_count ||
b.unix_time - a.unix_time;
})
console.log(data)