1

How do I sort this kind of map using the field lastSeen

var clients = new Map();
clients.set("BOJ_iPWtI7jVvG_pAAAH", {name: "John", lastSeen: 1608192766697});
clients.set("cShpndAsircj4_P4AAAN", {name: "Doe", lastSeen: 1608192862339});

How do I sort this clients map using lastSeen.

I have tried like this:

var sortedClients = new Map([...clients.entries()].sort((a,b)=>b.lastSeen - a.lastSeen));

but it is not working so I know I am not doing the right thing.

1
  • 1
    log a and b values inside the compareFunction. entries returns an array of key-value pairs. So, a will be something like: ["BOJ_iPWtI7jVvG_pAAAH", {name: "John", lastSeen: 1608192766697}] Commented Dec 17, 2020 at 8:39

2 Answers 2

3

Use b[1].lastSeen instead of b.lastSeen and the same for a as well, because the attribute lastSeen is actually in index 1 for each entry in clients.

var sortedClients = new Map([...clients.entries()].sort((a,b)=>b[1].lastSeen - a[1].lastSeen));
Sign up to request clarification or add additional context in comments.

Comments

2

You can do the following,

var clients = new Map();
clients.set("BOJ_iPWtI7jVvG_pAAAH", {name: "John", lastSeen: 1608192766697});
clients.set("cShpndAsircj4_P4AAAN", {name: "Doe", lastSeen: 1608192862339});
var mapAsc = new Map([...clients.entries()].sort((a, b) => {
  if(a[1].lastSeen > b[1].lastSeen) {
    return -1;
  } else if(a[1].lastSeen < b[1].lastSeen) {
    return 1;
  } else {
    return 0;
  }
}));
console.log(mapAsc);

1 Comment

Thanks to your answer, I understand what goes on inside the sort(); but I'll accept @PIG208 answer cause it's precise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.