0

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

  • Can you please make your stackblitz a bit better , something should be there to display like console log or any other thing so that we can get an idea of what the result currently you have – Fahad Subzwari Apr 04 '19 at 08:41
  • If you want to display just a key values and sort them by descending order you can use this line Object.keys(this.listaOrdinata).reverse() – Sarkani Apr 04 '19 at 08:47

1 Answers1

0

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));
beegotsy
  • 93
  • 10
  • It's what I wanted !! But if I were to enter numbers as a key? es. 2018 - 2019 etc ... instead of z, b, a, c? – Antonio Di Giulio Apr 04 '19 at 09:43
  • @AntonioDiGiulio with numbers should work as fine as with characters or string, it's the basic sorting function that you would find usually in any languages. Remember that numbers come before chars and strings – beegotsy Apr 04 '19 at 09:46
  • with numbers it doesn't work! https://stackblitz.com/edit/angular-a1yfkd what am I doing wrong? I want them in descending order – Antonio Di Giulio Apr 04 '19 at 09:48
  • @AntonioDiGiulio I think it has do to with the console.log method or other things, check this answer and maybe your initial code was correct https://stackoverflow.com/questions/39054764/show-original-order-of-object-properties-in-console-log – beegotsy Apr 04 '19 at 09:53
  • I don't think it's a console.log problem... stackblitz.com/edit/angular-a1yfkd – Antonio Di Giulio Apr 04 '19 at 10:04