I have a list with key-value pairs that I want to sort in descending order.
Here's one way to achieve that:
- Convert the keys of your map into a string array,
- Sort the keys (you can use a custom sorting function if needed),
- Create a new object by iterating through the sorted keys and populate it, then return it.
Does this method work for you?
const unsortedList: any = {
z: 'last',
b: '2nd',
a: '1st',
c: '3rd'
};
function sort(unsortedList: any): any {
const keys: string[] = Object.keys(unsortedList);
const sortedKeys = keys.sort().reverse(); //reverse if necessary
const sortedList: any = {};
sortedKeys.forEach(x => {
sortedList[x] = unsortedList[x];
});
return sortedList;
}
function sortWithoutUselessVariables(unsortedList: any): any {
const sortedList: any = {};
Object.keys(unsortedList)
.sort() // or pass a custom compareFn there, faster than using .reverse()
.reverse()
.forEach(x => sortedList[x] = unsortedList[x])
return sortedList;
}
console.log('unsorted:', unsortedList);
console.log('sorted:', sort(unsortedList));