Javascript sort array using two keys -


hi working on chat application, want sort new messages plus keeping history order according time.

for example, have chat messages in array 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 sort them using "msg_count" key greater values should come on top remaining objects should sorted "unix_time" key.

use array#sort method 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 difference of `msg_count` property sort based on them    // if equal sort based on unix_time prop    return b.msg_count - a.msg_count ||       b.unix_time - a.unix_time;  })    console.log(data)


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -