gpt4 book ai didi

javascript - JS 按特定字符串属性对对象数组进行排序(不是升序或降序)

转载 作者:行者123 更新时间:2023-12-05 01:32:16 24 4
gpt4 key购买 nike

您知道是否有一种方法可以使用特定属性的 sort() 方法对对象数组进行排序?在我的例子中,我想首先为“香蕉”对我的数组进行排序,然后为“梨”排序,然后是其余的。

const initialData = [
{ name: "strawberries", value: 12 },
{ name: "bananas", value: 3 },
{ name: "pears", value: 8 },
{ name: "pears", value: 7 },
{ name: "bananas", value: 10 },
{ name: "apples", value: 6 },
{ name: "bananas", value: 13 },
{ name: "bananas", value: 5 }
]

这就是我希望排序后的数据的样子:

const sortedData = [
{ name: "bananas", value: 3 },
{ name: "bananas", value: 10 },
{ name: "bananas", value: 13 },
{ name: "bananas", value: 5 },
{ name: "pears", value: 8 },
{ name: "pears", value: 7 },
{ name: "strawberries", value: 12 },
{ name: "apples", value: 6 }
]

我知道这个函数会按升序或降序对我的数据进行排序:

initialData.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});

最佳答案

您可以采用所需顺序的对象,并采用较大的值作为默认值进行排序。

const
data = [{ name: "strawberries", value: 12 }, { name: "bananas", value: 3 }, { name: "pears", value: 8 }, { name: "pears", value: 7 }, { name: "bananas", value: 10 }, { name: "apples", value: 6 }, { name: "bananas", value: 13 }, { name: "bananas", value: 5 }],
order = { bananas: 1, pears: 2 };

data.sort((a, b) => (order[a.name] || Number.MAX_VALUE) - (order[b.name] || Number.MAX_VALUE));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - JS 按特定字符串属性对对象数组进行排序(不是升序或降序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65687818/

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