Sort a JavaScript object
15 March 2022 (Updated 6 April 2022)
You want a function that takes an object and a comparison function, and returns the object sorted using the comparison function. Something like this:
// Sort by numeric value
sortObject(
{ 'John': 100, 'Alice': 300, 'Bob': 200 },
(a, b) => a[1] - b[1]
)
// { John: 100, Bob: 200, Alice: 300 }
// Sort by key
sortObject(
{ 'John': 100, 'Alice': 300, 'Bob': 200 },
(a, b) => a[0].localeCompare(b[0])
)
// { Alice: 300, Bob: 200, John: 100 }
Here’s how:
const sortObject = (obj, compareFn) => {
return Object
.entries(obj)
.sort(compareFn)
.reduce((sortedObj, [key, val]) => {
return { ...sortedObj, [key]: val }
}, {})
}
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment