Tuna Tuna - 1 month ago 6
Javascript Question

Javascript sort array using two keys

Hi am working on a chat application, I want to sort new messages plus keeping the history order according to time.

For example, I have the chat messages in an array like this

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


How can I also sort them using the "msg_count" key where all greater values should come on the top but the remaining objects should be sorted with the "unix_time" key.

Answer

Use Array#sort method with custom compare function.

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)