Created
November 1, 2021 03:17
-
-
Save DoctorDerek/06f06c2195cb86fd8dd9574d58e85e38 to your computer and use it in GitHub Desktop.
How to Sort an Object by Key or Property Name in JavaScript by Dr. Derek Austin ๐ฅณ https://medium.com/p/a8c07b179901
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" => "๐ฎ"} | |
const unsortedObjArr = [...Object.entries(myObj)] | |
const sortedObjArr = unsortedObjArr.sort(([key1, value1], [key2, value2]) => | |
key1.localeCompare(key2) | |
) | |
const sortedObject = {} | |
sortedObjArr.forEach(([key, value]) => (sortedObject[key] = value)) | |
console.log(sortedObject) | |
// {Goodnight: "๐", Hello: "๐", Hola: "๐ฎ"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment