Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DoctorDerek/06f06c2195cb86fd8dd9574d58e85e38 to your computer and use it in GitHub Desktop.
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
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