shahabvshahabi
shahabvshahabi

Reputation: 955

sorting an object inside of an array from A-Z

i have an object like below now i want to sort it from A-Z in javascript how can i sort it ?

[
    {"country" :"NG", "code" : "00234"}, 
    {"country" :"NZ", "code" : "0064"}, 
    {"country" :"NP", "code" : "00977"}, 
    {"country" :"NR", "code" : "00674"}, 
    {"country" :"NU", "code" : "00683"}, 
    {"country" :"CK", "code" : "00682"}, 
    {"country" :"CI", "code" : "00225"}, 
    {"country" :"CH", "code" : "0041"}, 
    {"country" :"CO", "code" : "0057"}, 
    {"country" :"CN", "code" : "0086"}, 
    {"country" :"CM", "code" : "00237"}, 
    {"country" :"CL", "code" : "0056"}, 
    {"country" :"CC", "code" : "0061"},  
    {"country" :"CA", "code" : "001"}, 
    {"country" :"CG", "code" : "00242"}, 
]

Upvotes: 0

Views: 40

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222682

You can use array.sort.

var myarray = [
    {"country" :"NG", "code" : "00234"}, 
    {"country" :"NZ", "code" : "0064"}, 
    {"country" :"NP", "code" : "00977"}, 
    {"country" :"NR", "code" : "00674"}, 
    {"country" :"NU", "code" : "00683"}, 
    {"country" :"CK", "code" : "00682"}, 
    {"country" :"CI", "code" : "00225"}, 
    {"country" :"CH", "code" : "0041"}, 
    {"country" :"CO", "code" : "0057"}, 
    {"country" :"CN", "code" : "0086"}, 
    {"country" :"CM", "code" : "00237"}, 
    {"country" :"CL", "code" : "0056"}, 
    {"country" :"CC", "code" : "0061"},  
    {"country" :"CA", "code" : "001"}, 
    {"country" :"CG", "code" : "00242"},
];

var sorted = myarray.sort((a, b) => a.country.localeCompare(b.country));

console.log(sorted);

Upvotes: 1

Related Questions