Another javascript array in alphabetical order

I have arrayone that looks like this: how can I sort it alphabetically without losing a key?

var items = [
  { 11: 'Edward' },
  { 12: 'Sharpe' },
  { 13: 'Alvin' }
];
+6
source share
3 answers

You can sort the array itemswith 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);
Run codeHide result
+6
source

If the objects have only one key, you can use Object.keysto extract this key and then sort:

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

items.sort(function(a, b) {
  var akey = Object.keys(a) [0],           // get a key
      bkey = Object.keys(b) [0];           // get b key
      
  return a[akey].localeCompare(b[bkey]);   // compare the values using those keys
});

console.log(items);
Run codeHide result
+6
source

Object.keys, , , length , .

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

items.sort(function(a, b){
 var c = Object.keys(a);
 var d = Object.keys(b);
 return a[c[c.length-1]] > b[d[d.length-1]] ? 1: -1;
 }
)

console.log(items);
Hide result
+1

All Articles