Skip to content

Instantly share code, notes, and snippets.

@amnuts
Created June 14, 2017 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amnuts/77e8a666e8c971c3e5e2fd74c5e53d77 to your computer and use it in GitHub Desktop.
Save amnuts/77e8a666e8c971c3e5e2fd74c5e53d77 to your computer and use it in GitHub Desktop.
Sort js hash, retaining key association
// 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