In order to sort a Map, you need to create a new Map with the items added in sorted order. For more information on sorting a Map, you can refer to this thread about sorting an ES6 map object.
To generate a sorted Map:
- Convert the Map entries into an array, for example:
[...map]
. Each entry will be represented as an array with [0] as the key and [1] as the value.
- Sort the array based on a specific property of the values, e.g.
.sort((a, b) => a[1].lastChat.time - b[1].lastChat.time)
.
- Create a new Map using the sorted result.
Below is an example using the time property mentioned in the original question:
const map = new Map();
map.set('0001', {lastChat: {message: 'test', time: 1640063014931}});
map.set('0002', {lastChat: {message: 'test', time: 1640063014930}});
const sortedMap = new Map([...map].sort((a, b) => a[1].lastChat.time - b[1].lastChat.time));
console.log(sortedMap.entries())
// Output: MapIterator {'0002' => {...}, '0001' => {...}}
If there's a possibility of null values in lastChat, additional logic needs to be implemented within the sorting function.