Created
June 14, 2017 08:49
-
-
Save amnuts/77e8a666e8c971c3e5e2fd74c5e53d77 to your computer and use it in GitHub Desktop.
Sort js hash, retaining key association
This file contains 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
// From: https://stackoverflow.com/a/36079484 | |
// The unsorted data | |
let data = { | |
a: 'A', | |
c: 'C', | |
b: 'B' | |
}; | |
// Create it sorted | |
const hash = Object.keys(data) | |
.map(key => ({k: key, v: data[key]})) | |
.sort((a, b) => a.v.localeCompare(b.v)) | |
.reduce((o, e) => { | |
o[e.k] = e.v; | |
return o; | |
}, {}); | |
// Display the sorted result | |
Object.getOwnPropertyNames(hash).forEach(n => { | |
snippet.log("hash['" + n + "'] = " + hash[n]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment