Created
September 19, 2018 08:31
-
-
Save LukeChannings/7bc92510288d7da1b3fedcc42a34cb7b to your computer and use it in GitHub Desktop.
rsort - recursively sort a data structure
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 rsort = data => { | |
if (Array.isArray(data)) { | |
if (data.every(a => /(string|number|undefined)/.test(typeof a) || a === null)) return data.sort() | |
return data.map(rsort).sort() | |
} | |
if (typeof data === 'object' && data !== null) { | |
return Object.entries(data) | |
.sort(([k], [_k]) => k > _k) | |
.reduce((o, [k, v]) => ({ ...o, [k]: rsort(v) }), {}) | |
} | |
return data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Paste
rsort
into DevTools (or save as a snippet), and use like:copy(rsort(someData))