5

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?

asked Nov 19, 2013 at 22:22
2
  • 3
    possible duplicate of Sorting an array of JavaScript objects Commented Nov 19, 2013 at 22:24
  • It's not a duplicate. That question wanted to sort by a known key that exists in each object in the array. This question wants to sort by the key name itself, which is different from object to object. Commented Nov 20, 2013 at 14:43

2 Answers 2

8

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

mquandalle
2,59822 silver badges24 bronze badges
answered Nov 19, 2013 at 22:26
Sign up to request clarification or add additional context in comments.

1 Comment

Why the "- 0.5" though?
0

PSL's answer have one problem that is if your array has uppercase and lowercase keys i.e. "john", "Naveed" then this solution is not going to work correctly. Following changes need to be done:

let source = [{"john": 12},{"Ali": 10},{"Naveed": 18}];
var target = source.sort(function(a,b){
 return (Object.keys(a)[0].toLowerCase() > Object.keys(b)[0].toLowerCase()) - 0.5;
});
console.log(target);
answered Jul 9, 2021 at 6:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.