Tuna Tuna - 6 days ago 4x
Javascript Question

Javascript sort array in order

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

For example i have the chat messages in an array like this, now am sorting them using the "time" key on each message object!

[{"user":"a", "msg":"Hi ", "read":true, "time":1}
{"user":"b", "msg":"Hi ", "read":false, "time":2}
{"user":"c", "msg":"Hi ", "read":false, "time":3}
{"user":"d", "msg":"Hi ", "read":true, "time":4}
{"user":"e", "msg":"Hi ", "read":true, "time":5}]

How can i also sort them using the "read" key where all false values should come on the top but the remaining objects should be sorted with the "time" key.

For example like this

[{"user":"b", "msg":"Hi ", "read":false, "time":2}
{"user":"c", "msg":"Hi ", "read":false, "time":3}
{"user":"a", "msg":"Hi ", "read":true, "time":1}
{"user":"d", "msg":"Hi ", "read":true, "time":4}
{"user":"e", "msg":"Hi ", "read":true, "time":5}]


You could use Array#sort and a callback for the sort order and chain the wanted sort parameter.

This callback uses the implicit converting of boolean to number with a calculation.

var array = [{ "user": "a", "msg": "Hi ", "read": true, "time": 1 }, { "user": "b", "msg": "Hi ", "read": false, "time": 2 }, { "user": "c", "msg": "Hi ", "read": false, "time": 3 }, { "user": "d", "msg": "Hi ", "read": true, "time": 4 }, { "user": "e", "msg": "Hi ", "read": true, "time": 5 }];

array.sort(function (a, b) {
    return a.read - b.read || a.time - b.time;

.as-console-wrapper { max-height: 100% !important; top: 0; }