Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' }
];
like image 991
Gibran Ibrahim Avatar asked Aug 24 '17 22:08

Gibran Ibrahim


People also ask

How do you sort an array of objects alphabetically in JavaScript?

JavaScript arrays have the sort( ) method, which sorts the array elements into alphabetical order. The sort( ) method accepts a function that compares two items of the Array. sort([comparer]) .

How do I sort a list in alphabetical order in JavaScript?

We can do this in JavaScript by using the sort() method directly or with the compare function. In case you are in a rush, here are the two ways: // order an array of names names. sort(); // order an array of objects with name users.

Does sort mutate array JavaScript?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


1 Answers

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);
like image 62
Erazihel Avatar answered Sep 27 '22 21:09

Erazihel