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' }
];
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]) .
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.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With