Skip to content

Instantly share code, notes, and snippets.

@jrc03c
Last active May 29, 2023 01:07
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 jrc03c/41d6aa33b23feb14741a4c373c7c5b59 to your computer and use it in GitHub Desktop.
Save jrc03c/41d6aa33b23feb14741a4c373c7c5b59 to your computer and use it in GitHub Desktop.
Recursively / deeply sort an object or array in JS
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