我试图了解如何按整数值对 JavaScript 对象数组进行排序。然而,在网上查看了一些以前的解决方案后,我并没有太多运气。我怀疑这可能是由于我构建数组的方式造成的,但由于缺乏知识,我不确定原因。
当我寻找指导时,很多示例都显示了可访问的通用 key 名称,但是,我更愿意使用不同的 key 属性,如下所示。
我有一个 JavaScript 对象数组,如下所示:
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {Avobath_Count: "5"}
1: {DragonsEgg_Count: "3"}
2: {Intergalactic_Count: "2"}
3: {Twilight_Count: "9"}
4: {SexBomb_Count: "6"}
5: {TheExperimenter_Count: "6"}
6: {TurtleImmersion_Count: "5"}
7: {Butterball_Count: "3"}
8: {MarshmallowWorld_Count: "0"}
9: {ThinkPink_Count: "2"}
我尝试过使用:
keysSorted = Object.keys(presentationOrder).sort(function(a,b){return presentationOrder[a]-presentationOrder[b]}).map(key => presentationOrder[key]);
但是,这并没有根据值对我的数组进行从高到低的排序。
我想让我的数组显示如下:
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {Twilight_Count: "9"}
1: {SexBomb_Count: "6"}
2: {TheExperimenter_Count: "6"}
3: {Avobath_Count: "5"}
4: {TurtleImmersion_Count: "5"}
5: {Butterball_Count: "3"}
6: {DragonsEgg_Count: "3"}
7: {Intergalactic_Count: "2"}
8: {ThinkPink_Count: "2"}
9: {MarshmallowWorld_Count: "0"}
任何指导将不胜感激。
最佳答案
如果数组中的所有对象
只有一对键值
,那么您可以使用Object.values()在 sort()
方法中:
let input = [
{Avobath_Count: "5"},
{DragonsEgg_Count: "3"},
{Intergalactic_Count: "2"},
{Twilight_Count: "9"},
{SexBomb_Count: "6"},
{TheExperimenter_Count: "6"},
{TurtleImmersion_Count: "5"},
{Butterball_Count: "3"},
{MarshmallowWorld_Count: "0"},
{ThinkPink_Count: "2"}
];
input.sort((a ,b) => Object.values(b)[0] - Object.values(a)[0]);
console.log(input);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
或者,您也可以使用 Object.entries()也是:
let input = [
{Avobath_Count: "5"},
{DragonsEgg_Count: "3"},
{Intergalactic_Count: "2"},
{Twilight_Count: "9"},
{SexBomb_Count: "6"},
{TheExperimenter_Count: "6"},
{TurtleImmersion_Count: "5"},
{Butterball_Count: "3"},
{MarshmallowWorld_Count: "0"},
{ThinkPink_Count: "2"}
];
input.sort((a, b) => Object.entries(b)[0][1] - Object.entries(a)[0][1]);
console.log(input);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
关于javascript - 当键具有不同名称时对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55731414/