[英]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.