I have an alternative solution to the methods which are mentioned over here.
First, we convert the object to array. Next, we have to provide a custom sorting function. We sort it by making use of localeCompare, and passing the numeric: true
option to localeCompare. I have left the locale as undefined
, but you may pass in your own locale options, depending on your use case.
const obj = {
64: {id: "83", name: "(83) x"},
65: {id: "84", name: "(84) y"},
66: {id: "85", name: "(85) z"},
67: {id: "86", name: "(86) a"},
68: {id: "9", name: "(9) b"}
}
const result = Object.values(obj).sort((a,b) => {
return a['id'].localeCompare(b['id'], undefined, {numeric: true});
});
console.log(result);
If you would prefer to squeeze everything onto one line,
const result = Object.values(obj).sort((a,b) => a['id'].localeCompare(b['id'],undefined, {numeric: true}));
Please read up more about JavaScript's sort method, as I have noticed that you are trying to 'directly' sort an object/dictionary using JavaScript's sort. It has to be in array format.