简体   繁体   English

按不起作用的键对对象数组进行排序

[英]Sort array of objects by keys not working

I have this array of objects:我有这个对象数组:

 let ans = [{'a' : 5},{'d' : 3 },{'c' : 0 },{'b' : 4 }]; //Attempt to sort this ans.sort((a,b)=>{ return Object.keys(a)[0] > Object.keys(b)[0]; }); console.log(ans);

Shouldn't this sort function sort it?这个排序函数不应该排序吗? If not this how to sort this.如果不是这如何排序。

The function provided for array.sort() should return a number instead of a boolean.array.sort()提供的函数应该返回一个数字而不是一个布尔值。 If a > b , then a number greater than 0 should be returned.如果a > b ,则应返回大于 0 的数字。 If a < b , then a number less than 0.如果a < b ,则为小于 0 的数。

 let ans = [{'a' : 5},{'d' : 3 },{'c' : 0 },{'b' : 4 }]; //Attempt to sort this console.log(ans.sort((a,b)=>{ return Object.keys(a)[0] > Object.keys(b)[0] ? 1 : -1; }));

Alternatively you can use localeCompare或者,您可以使用localeCompare

ans.sort((a,b)=>{
    return Object.keys(a)[0].localeCompare(Object.keys(b)[0]);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM