Search code examples
javascriptarrayssortingjscriptalphabetical

Another javascript array alphabetical sorting hardtime


I have an array that looks like this, how can I sort it alphabetically without loosing the key?

var items = [
  { 11: 'Edward' },
  { 12: 'Sharpe' },
  { 13: 'Alvin' }
];

Solution

  • You can sort the items array using Object.values.

    const items = [
      { 11: 'Edward' },
      { 12: 'Sharpe' },
      { 13: 'Alvin' }
    ];
    
    items.sort((a, b) => Object.values(a)[0] > Object.values(b)[0]);
    
    console.log(items);