从A-Z中对数组内的对象进行排序

时间:2017-11-23 18:43:43

标签: javascript sorting

我有一个类似下面的对象现在我想在javascript中从A-Z中对它进行排序我该怎么排序呢?

[
    {"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"}, 
]

1 个答案:

答案 0 :(得分:1)

您可以使用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);