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

标签 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"}, 
]

最佳答案

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

关于javascript - 从 A-Z 顺序对数组内的对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47461762/

相关文章:

javascript - 在键数组中使用 startkey&endkey 时出现 CouchDB 错误

javascript - `Experimental decorator usage` 的流类型消除警告

arrays - k-最大元素优化 Swift 3.0

java - java中用于对对象数组进行排序的比较函数?

javascript - 无法从 Angular JS 的 Controller 函数中访问 $scope 变量

javascript - Vue SFC/vue-loader/webpack 样式包含顺序

c# - 使用 COM-Interop 将数组从 JS 返回到 C#

linux - 根据 bash 中给出的键进行排序

arrays - 在 O(n) 时间内合并具有常量内存的数组的两个排序部分

c++ - 冒泡排序 - 结构数组与结构数组