Home > Back-end >  How to sort a specific value in a map
How to sort a specific value in a map

Time:12-22

I would like to sort my map by the value "time". But I do not know how to do. I googled a lot but I can't make it work.

Maybe someone could help me please.

My Map looks like this:

this.map.set(userData.data()['uid'], { data: userData.data(), lastChat: {message: messages[0].msg, time: messages[0].time}});

uid: {
      data: sampleData,
      lastChat: {
                 message: "A sample text"
                 time: 1640063014931
      }
}

CodePudding user response:

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:

  1. 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.
  2. Sort the array on the time property from the value .sort((a, b) => a[1].lastChat.time - b[1].lastChat.time).
  3. 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.

  • Related