2016-11-08 49 views
-1

您好我正在開發一個聊天應用程序,我想對新消息進行排序,並根據時間保留歷史順序。使用兩個鍵的Javascript排序數組

例如,我有聊天消息在這樣

[{"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

你可以使用data.sort() – Vikrant

+0

可能是你正在尋找這個http://stackoverflow.com/questions/6913512/how-to-sort-an-array-對象由多個字段 – Nitheesh

+2

@Cerbrus你甚至讀過我的問題嗎?我有一個數字和一個字符串屬性來排序!所有這些鏈接都沒有! – Tuna

回答

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)

+0

不錯的一個,你可以添加unix_time鍵的排序嗎 – Tuna

+0

@Tuna:他已經在那裏實現了'unix_time'排序。 – Cerbrus

+0

@Tuna:以何種順序 –