find the smallest value in a map in javascript

To find the smallest value in a map, you can convert the map to an array using the spread operator, and then use the Math.min() function to find the smallest value. Here's an example:

index.tsx
const myMap = new Map([
  ['a', 10],
  ['b', 5],
  ['c', 20]
]);

const myArray = [...myMap.values()]; // Convert map values to array

const minVal = Math.min(...myArray); // Find smallest value using spread operator

console.log(minVal); // Output: 5
252 chars
12 lines

Alternatively, you can use the Array.from() method to create an array from the map and then use the Array.prototype.sort() method to sort the values in ascending order, and then return the first element of the sorted array:

index.tsx
const myMap = new Map([
  ['a', 10],
  ['b', 5],
  ['c', 20]
]);

const sortedArray = Array.from(myMap.values()).sort((a, b) => a - b); // Sort array in ascending order

const minVal = sortedArray[0];

console.log(minVal); // Output: 5
236 chars
12 lines

gistlibby LogSnag