1

I want to sort and array of objects with the property key name. My Array of objects looks like this:

var array = [
  {
     'version2': {
        name: 'abc'
     }
  }, 
  {
     'version1': {
        name: 'xyz'
     }
  }
]

The output expected is something like this:

var array = [
  {
     'version1': {
        name: 'xyz'
     }
  }, 
  {
     'version2': {
        name: 'abc'
     }
  }
]

I tried sorting with this solution but no luck

var abc = array.sort(function(a, b){return Object.keys(a)[0] - Object.keys(b)[0]});
console.log(abc);

The output was same. Please help me out with the solution. Thank you.

Tales
  • 269
  • 3
  • 14
  • @Taki No, the answer on the mentioned portal sort by key value and I needed the sorting key name. – Tales Apr 12 '21 at 06:18

2 Answers2

2

You can use localeCompare. Assuming each of the objects have only one key

var array = [{
    'version2': {
      name: 'abc'
    }
  },
  {
    'version1': {
      name: 'xyz'
    }
  }
]
const sorted = array.sort((a, b) => {
  return Object.keys(a)[0].localeCompare(Object.keys(b)[0])
});
console.log(sorted)
brk
  • 48,835
  • 10
  • 56
  • 78
0

Change this line (compare expression):

var abc = array.sort(function(a, b){return (Object.keys(a)[0] > Object.keys(b)[0])? 1: -1});

Or just:

var abc = array.sort((a, b) => (Object.keys(a)[0] > Object.keys(b)[0])? 1: -1);
saeedkazemi
  • 321
  • 1
  • 5