0

If I have a Map, defined like so:

let map: Map<string, number> = new Map();

map.set("a", 12);
map.set("b", 124);
map.set("c", 14);
map.set("d", 155);

How would I get the key of the biggest value, in this case, the output would be "d"

I've tried a few answers that work with Object's(i.e {}) but none of those work since they access the object using obj[key].

Typescript Playground link with the code: here

2 Answers 2

1

Using Array.from() and Array.reduce(), this could be done as follows:

Array.from(map.entries()).reduce((a, b) => a[1] < b[1] ? b : a)[0];
Sign up to request clarification or add additional context in comments.

Comments

0

Here is one approach

  • Convert it to an array of key/value pairs
  • Sort the array by the value
  • Extract the second item of the first pair

Like so

let map: Map<string, number> = new Map();

map.set("a", 12);
map.set("b", 124);
map.set("c", 14);
map.set("d", 155);

const key = Array.from(map).sort((a, b) => (a[1] > b[1] ? -1 : 1))[0][0];

console.log(key);

Comments

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.