Last active
May 29, 2023 01:07
-
-
Save jrc03c/41d6aa33b23feb14741a4c373c7c5b59 to your computer and use it in GitHub Desktop.
Recursively / deeply sort an object or array in JS
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
function deepSort(x, fn) { | |
fn = fn || ((a, b) => (a < b ? -1 : 1)) | |
if (typeof x === "object") { | |
if (x === null) return x | |
if (x instanceof Array) { | |
return x.map(v => deepSort(v, fn)).sort(fn) | |
} | |
else { | |
const out = {} | |
const keys = Object.keys(x).sort(fn) | |
keys.forEach(key => { | |
out[key] = deepSort(x[key], fn) | |
}) | |
return out | |
} | |
} | |
return x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment