Skip to content

Instantly share code, notes, and snippets.

@reececomo
Last active June 14, 2024 11:37
Show Gist options
  • Select an option

  • Save reececomo/e3ad7d288b85d2b7e7c854816b970bf2 to your computer and use it in GitHub Desktop.

Select an option

Save reececomo/e3ad7d288b85d2b7e7c854816b970bf2 to your computer and use it in GitHub Desktop.
Sort an object in place or by copy (TypeScript/JavaScript)
// JavaScript versions at the bottom
// ----- TypeScript: -----
type ObjectCompareFn = (a: string, b: string) => number;
/** Sorts an object in place */
export function sortObject<T extends object>(obj: T, compareFn?: ObjectCompareFn): T {
Object.keys(obj).sort(compareFn).forEach(key => {
const value = obj[key];
delete obj[key];
obj[key] = value;
});
return obj;
}
/** Returns a sorted copy of an object */
export function sortedObject<T extends object>(obj: T, compareFn?: ObjectCompareFn): T {
return Object.keys(obj).sort(compareFn).reduce((copy, key) => {
copy[key] = obj[key];
return copy;
}, {}) as T;
}
// ----- JavaScript: -----
/**
* Sorts an object in place
* @param {T} obj
* @param {undefined(string, string) => number} compareFn
* @returns {T} reference to obj
*/
function sortObject(obj, compareFn) {
Object.keys(obj).sort(compareFn).forEach(key => {
const value = obj[key];
delete obj[key];
obj[key] = value;
});
return obj;
}
/**
* Returns a sorted copy of an object
* @param {T} obj
* @param {undefined | (string, string) => number} compareFn
* @returns {T}
*/
function sortedObject(obj, compareFn) {
return Object.keys(obj).sort(compareFn).reduce((copy, key) => {
copy[key] = obj[key];
return copy;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment