Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DoctorDerek/b188a1c606c8bc9b36b281eecb0779c1 to your computer and use it in GitHub Desktop.
Save DoctorDerek/b188a1c606c8bc9b36b281eecb0779c1 to your computer and use it in GitHub Desktop.
How to Sort a Map in JavaScript https://medium.com/p/59751f06f692
const myObj = { Hello: "๐ŸŒŽ", Goodnight: "๐ŸŒ›", Hola: "๐ŸŒฎ" }
const unsortedMap = new Map(Object.entries(myObj))
console.log(unsortedMap)
// Map(3) {"Hello" => "๐ŸŒŽ", "Goodnight" => "๐ŸŒ›", "Hola" => "๐ŸŒฎ"}
// Step 1: Turn the Map into an array
const unsortedArray = [...unsortedMap] // same as Array.from
// Step 2: Sort the array with a callback function
const sortedArray = unsortedArray.sort(([key1, value1], [key2, value2]) =>
key1.localeCompare(key2)
) // Compare to numerically sorting an array with .sort((a, b) => a-b)
// Step 3: Turn the array back into a Map
const sortedMap = new Map(sortedArray)
console.log(sortedMap)
// Map(3) { "Goodnight" => "๐ŸŒ›", "Hello" => "๐ŸŒŽ", "Hola" => "๐ŸŒฎ"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment