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' }
];
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' }
];
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);
Internet Explorer.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);
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);