Maps iterate in the order the items are added, to sort a map you must generate a new map adding the items in the sorted order. Further details on sorting a Map can be found at Is it possible to sort a ES6 map object?.
To generate a new sorted Map you can:
- Place the entries from the map into an array e.g.
[...map]
. Each entry will be added as an array where [0] is the key and [1] is the value.
- Sort the array on the time property from the value
.sort((a, b) => a[1].lastChat.time - b[1].lastChat.time)
.
- Generate a new Map with the result
Below is an example based on the property mentioned in the question.
var map = new Map();
map.set('0001', {lastChat: {message: 'test', time: 1640063014931}});
map.set('0002', {lastChat: {message: 'test', time: 1640063014930}});
var sortedMap = new Map([...map].sort((a, b) => a[1].lastChat.time - b[1].lastChat.time));
console.log(sortedMap.entries())
//Output : MapIterator {'0002' => {…}, '0001' => {…}}
If lastChat can be null then you'd need to expand the sort function with additional logic for this.