Created
August 30, 2021 03:40
-
-
Save DoctorDerek/b188a1c606c8bc9b36b281eecb0779c1 to your computer and use it in GitHub Desktop.
How to Sort a Map in JavaScript https://medium.com/p/59751f06f692
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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