gpt4 book ai didi

javascript - 对对象的javascript数组进行排序

转载 作者:行者123 更新时间:2023-11-29 19:59:12 24 4
gpt4 key购买 nike

我有一个如下所示的数组:

data = 
[
{name: "Monday", amount: 67, colour: "red"},

{name: "Tuesday", amount: 23, colour: "blue"},

{name: "Wednesday", amount: 50, colour: "yellow"},

{name: "Thursday", amount: 70, colour: "green"},

{name: "Friday", amount: 20, colour: "orange"},

{name: "Saturday", amount: 90, colour: "black"},

{name: "Sunday", amount: 10, colour: "brown"}
]

我想按“金额”值降序对数组进行排序,因此排序后,数组将如下所示:

data = 
[
{name: "Saturday", amount: 90, colour: "black"},

{name: "Thursday", amount: 70, colour: "green"},

{name: "Monday", amount: 67, colour: "red"},

{name: "Wednesday", amount: 50, colour: "yellow"},

{name: "Tuesday", amount: 23, colour: "blue"},

{name: "Friday", amount: 20, colour: "orange"},

{name: "Sunday", amount: 10, colour: "brown"}
]

我在 stackoverflow 上看到过各种与此类似的帖子,但我发现很难将这些问题解释为像我这样的问题,它具有命名索引(名称、数量、颜色),而不仅仅是 [0]、[ 1], [2]

最佳答案

使用Array.sort :

data.sort(function(a, b) {
return b.amount - a.amount;
});

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com