Skip to content

Instantly share code, notes, and snippets.

@amnuts amnuts/sort.js
Created Jun 14, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.