-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.

4
  • you can use data.sort() Commented Nov 8, 2016 at 10:49
  • May be you are looking for this stackoverflow.com/questions/6913512/… Commented Nov 8, 2016 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! Commented Nov 8, 2016 at 10:59
  • @Tuna: The concept is the same, but here's another example. Commented Nov 8, 2016 at 11:01

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

5 Comments

Nice one, could you please add sorting for the unix_time key as well
@Tuna: He already has sorting on unix_time implemented there.
@Tuna : in which order
@Pranav i mean the "unix_time" property of each object in the array
The Unix_time property is not affected by your function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.