If you prefer a more hands-on approach, or maybe you’re working with older JavaScript or just prefer avoiding higher-order functions, here’s a solution where we manually loop through the object using for...in
. This approach gives a lot more control over the sorting process and keeps everything within the standard JavaScript syntax.
function sortObjectByValue(obj) {
const keys = Object.keys(obj);
keys.sort((a, b) => obj[a] - obj[b]);
const sortedObj = {};
keys.forEach(key => {
sortedObj[key] = obj[key];
});
return sortedObj;
}
const list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
const sortedList = sortObjectByValue(list);
console.log(sortedList);
In this version, we first use Object.keys()
to get the array of keys. We then sort those keys by the values in the original object. After that, we loop through the sorted keys and create a new object with the correct order.
This method is simple, doesn’t require any additional array manipulation, and is perfect if you’re working in environments where you prefer sticking to traditional loops. It’s straightforward, and while it’s not as concise as the Object.entries()
version, it still achieves the same goal of sorting a javascript sort object
.