I created a key-value list, I would like to sort it in descending order
One way to do that can be
- take the keys of your map as a string array,
- sort the keys (if you need you can pass a custom sorting function)
- populate a new object iterating through the sorted keys and return it
Do this 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 you need or not
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));