user2454781
user2454781

Reputation: 1

Json object sort by ascending using javascript

I have a json object and i want to sort it by ascending order

  [{ d: "delte the text" }, { c: "copy the text" }]

The key d and c are dynamically created, next time may be changed. How I can sort this into

[{ c: "copy the text" }, { d: "delte the text" }]

Please help me how I can do this. Thanks!

Upvotes: 0

Views: 1617

Answers (1)

Jon
Jon

Reputation: 437376

To sort an array you use Array.sort with an appropriate comparison function as an argument. The comparison function accepts two arguments, which in this case are expected to be objects with just a single property. You want to sort based on the name of that property.

Getting an object's property names is most convenient with Object.keys, so we have this comparison function:

function(x, y) { 
    var keyX = Object.keys(x)[0], 
        keyY = Object.keys(y)[0]; 

    if (keyX == keyY) return 0; 
    return keyX < keyY ? -1 : 1;
}

It can be used like this:

var input = [{ d: "delete the text" }, { c: "copy the text" } ];
var sorted = input.sort(function(x, y) { 
    var keyX = Object.keys(x)[0], 
        keyY = Object.keys(y)[0]; 

    if (keyX == keyY) return 0; 
    return keyX < keyY ? -1 : 1;
});

See it in action.

Note that Object.keys requires a reasonably modern browser (in particular, IE version at least 9); otherwise you would need to write something such as this instead:

var keyX, keyY, name;
for (name in x) { keyX = name; break; }
for (name in y) { keyY = name; break; }

See it in action.

Upvotes: 1

Related Questions