Sorting an array of objects by keyname in javascript

arrays, javascript, object, sorting

Solution

Something like this using Array.sort(compareFunction) ?

var myArray =[{"qwe":4}, {"rty":5}, {"asd":2}];
myArray.sort(function(a,b){
    return (Object.keys(a)[0] > Object.keys(b)[0]) - 0.5;
});
console.log(myArray);

Demo

Problem

How do I sort this array: ``` [{"qwe":4}, {"rty":5}, {"asd":2}] ``` To get this: ``` [{"asd":2}, {"qwe":4}, {"rty":5}] ``` So that the array is sorted by the name of the key of the objects?

Original source

Related problems