-1

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.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Ceddy Muhoza
  • 636
  • 3
  • 17
  • 34
  • you can use data.sort() – Vikrant Nov 08 '16 at 10:49
  • May be you are looking for this http://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields – Nitheesh Nov 08 '16 at 10:51
  • 2
    @Cerbrus did you even read my question? i have a number and a string property to sort! All these links don't have none of that! – Ceddy Muhoza Nov 08 '16 at 10:59
  • @Tuna: The concept is the same, but here's [another example.](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Cerbrus Nov 08 '16 at 11:01

1 Answers1

1

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)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188