gpt4 book ai didi

javascript - 按自定义订单排序

转载 作者:行者123 更新时间:2023-12-02 23:10:15 25 4
gpt4 key购买 nike

我想知道如何按自定义顺序而不是按字母顺序对数组进行排序。想象一下你有这个数组/对象:

var somethingToSort = [{
type: "fruit",
name: "banana"
}, {
type: "candy",
name: "twix"
}, {
type: "vegetable",
name: "broccoli"
}, {
type: "vegetable",
name: "carrot"
}, {
type: "fruit",
name: "strawberry"
}, {
type: "candy",
name: "kitkat"
}, {
type: "fruit",
name: "apple"
}];

这里有 3 种不同的类型:水果、蔬菜和糖果。现在我想对这个数组进行排序,并确保所有水果都在前面,糖果在水果后面,蔬菜在最后。每种类型都需要按字母顺序对它们的项目进行排序。我们将使用类似 sortArrayOnOrder ( ["fruit","candy","vegetable"], "name" ); 的函数所以基本上,排序后你会得到这个数组:

var somethingToSort = [{
type: "fruit",
name: "apple"
}, {
type: "fruit",
name: "banana"
}, {
type: "fruit",
name: "strawberry"
}, {
type: "candy",
name: "kitkat"
}, {
type: "candy",
name: "twix"
}, {
type: "vegetable",
name: "broccoli"
}, {
type: "vegetable",
name: "carrot"
}];

有人知道如何为此创建脚本吗?

最佳答案

Cerbrus 代码的改进版本:

var ordering = {}, // map for efficient lookup of sortIndex
sortOrder = ['fruit','candy','vegetable'];
for (var i=0; i<sortOrder.length; i++)
ordering[sortOrder[i]] = i;

somethingToSort.sort( function(a, b) {
return (ordering[a.type] - ordering[b.type]) || a.name.localeCompare(b.name);
});

关于javascript - 按自定义订单排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14872554/

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