6

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' }
];
2
  • 1
    Does all object have only 1 key-value pair? Commented Aug 24, 2017 at 22:21
  • yes, numbers are keys, and names are values.. Commented Aug 24, 2017 at 22:57

3 Answers 3

6

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, will fail though on Internet Explorer.
6

If the objects have only one key, then you can use Object.keys to retrieve that key an then sort:

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

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

console.log(items);

Comments

1

By using Object.keys, since they only have one value we don't know, we can use the length property minus one to get the actual key reference.

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.