Created
August 30, 2021 03:44
-
-
Save DoctorDerek/eaac1cd8161a0ad893c1a1dfdfeaa1fa 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: "๐" } | |
| const myMap = new Map(Object.entries(myObj)) | |
| // Add an item | |
| myObj["Hola"] = "๐ฎ" | |
| myMap.set("Hola", "๐ฎ") | |
| // Get an item | |
| console.log(myObj["Hola"]) // ๐ฎ | |
| console.log(myMap.get("Hola")) // ๐ฎ | |
| // View the entire object or Map | |
| console.log(myObj) | |
| // {Hello: "๐", Goodnight: "๐", Hola: "๐ฎ"} | |
| console.log(myMap) | |
| // Map(3) {"Hello" => "๐", "Goodnight" => "๐", "Hola" => "๐ฎ"} | |
| // Turn an object into an array | |
| const myIterable = Object.entries(myObj) | |
| console.log(Array.from(myIterable)) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] | |
| console.log([...myIterable]) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] | |
| // Turn a Map into an array | |
| console.log(Array.from(myMap)) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] | |
| console.log([...myMap]) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] | |
| // Iterate over all items with for...of | |
| for (const o of myIterable) { | |
| console.log(o) | |
| } | |
| // ["Hello", "๐"] // ["Goodnight", "๐"] // ["Hola", "๐ฎ"] | |
| for (const m of myMap) { | |
| console.log(m) | |
| } | |
| // ["Hello", "๐"] // ["Goodnight", "๐"] // ["Hola", "๐ฎ"] | |
| // Iterate over all items with .forEach() | |
| Array.from(myIterable).forEach((a) => console.log(a)) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] | |
| Array.from(myIterable).forEach(([key, value]) => console.log([key, value])) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] | |
| myMap.forEach((value, key) => console.log([key, value])) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] | |
| Array.from(myMap).forEach(([key, value]) => console.log([key, value])) | |
| // [["Hello", "๐"], ["Goodnight", "๐"], ["Hola", "๐ฎ"]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment