'Ordering Map Object Angular

I have a problem: I created a key-value list, I would like to sort it in descending order. If you notice, in the stackblitz, I gave an example of how I create the list and with methods I try to sort it. but the result is always the same (sorts them in decreasing order)

n.b: I need a key-value list and not an array

Stack: https://stackblitz.com/edit/angular-a1yfkd



Solution 1:[1]

I created a key-value list, I would like to sort it in descending order

One way to do that can be

  1. take the keys of your map as a string array,
  2. sort the keys (if you need you can pass a custom sorting function)
  3. 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));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1