find the smallest key in a map in typescript

To find the smallest key in a Map in TypeScript, you can use the Math.min function along with the spread operator to convert the Map keys into an array of numbers. Here's the code:

index.ts
const myMap = new Map<number, string>();
myMap.set(1, 'one');
myMap.set(2, 'two');
myMap.set(3, 'three');

const smallestKey = Math.min(...Array.from(myMap.keys()));
console.log(smallestKey); // Output: 1
205 chars
8 lines

In this code, we first create a Map object called myMap and add some key-value pairs to it. Then, we use the Array.from method to convert the Map keys into an array of numbers. Finally, we apply the spread operator ... to this array and pass it as arguments to the Math.min function. This will return the smallest key in the Map, which we can store in the smallestKey constant and log to the console.

gistlibby LogSnag