可能重复:
Sort array of objects
[ { name: 'jane', id:'3' }
{ name: 'zac', id: '5' }
{ name: 'amber', id: '2 }
]
如何按名称按字母顺序对此进行排序?
结果应为:
[ { name: 'amber', id: '2' }
{ name: 'jane', id:'3' }
{ name: 'zac', id: '5' }
]
答案 0 :(得分:2)
使用Array.sort
。您可以将其传递给自定义函数以用于比较对象。要比较字符串,您可以使用String.localeCompare
。把它放在一起,你就明白了:
var data=[
{ name: 'jane', id: 3 }
{ name: 'zac', id: 5 }
{ name: 'amber', id: 2 }
];
console.log("Unsorted:", data);
data.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
console.log("Sorted:", data);
答案 1 :(得分:1)
[{ name: 'jane', id:'3' },
{ name: 'zac', id: '5'},
{ name: 'amber', id: '2'}].sort(
function (a,b) {
return a.name.localeCompare(b.name)
}
);