我想知道是否如何创建具有某种排序优先级的自定义 sortOn 函数。我有一个更复杂的案例,但我主要想知道如何构建好的排序函数。
假设我有这个带有数据对象的未排序列表:
var myList = [
{drink: {amount: 1, name: "cola"}},
{drink: {amount: 5, name: "beer"}},
{food: {amount: 7, name: "cake"}},
{drink: {amount: 3, name: "fanta"}},
{drink: {amount: 4, name: "tea}},
{other: {amount: 1, name: "table"}},
{food: {amount: 4, name: "mars"}},
{food: {amount: 5, name: "pizza"}},
{food: {amount: 4, name: "cake"}},
{other: {amount: 12, name: "chair"}},
{food: {amount: 14, name: "chips"}},
{drink: {amount: 6, name: "coffee}},
{food: {amount: 8, name: "chips"}},
{food: {amount: 6, name: "pizza"}},
{food: {amount: 1, name: "food"}}
]
好的,成像我想使用这些规则进行排序:
first: sort in this order: food, drinks, others (note, thats not alphabetical)
then: sort on amount, BUT on food, pizza's + cakes must be on top
在理想情况下,它看起来像这样(手动创建):
var myList = [
{food: {amount: 5, name: "pizza"}},
{food: {amount: 6, name: "pizza"}},
{food: {amount: 4, name: "cake"}},
{food: {amount: 7, name: "cake"}},
{food: {amount: 1, name: "food"}},
{food: {amount: 4, name: "mars"}},
{food: {amount: 8, name: "chips"}},
{food: {amount: 14, name: "chips"}},
{drink: {amount: 1, name: "cola"}},
{drink: {amount: 3, name: "fanta"}},
{drink: {amount: 4, name: "tea}},
{drink: {amount: 5, name: "beer"}},
{drink: {amount: 6, name: "coffee}},
{other: {amount: 1, name: "table"}},
{other: {amount: 12, name: "chair"}}
]
同样,这完全不是一个真实的例子,但我有一些案例(甚至更深的嵌套对象)我想应用这样的规则。
是否可以创建某种排序顺序查找列表(类似这样),还是不可行?
priorityList = [
food:[
name:["pizza", "tea", rest],
amount: Array.ASCENDING}
],
drink,
other
]; // etc..
我想学习如何制作这种排序功能。我喜欢看 Javascript 或 Actionscript 解决方案,但其他语言也可以说明。有这方面的图书馆吗?我是否必须遍历所有项目、创建条件、在情况下推送/取消移位,或者这是否可以通过自定义sort()
函数实现?我需要一些指导如何以实用/有效的方式解决这个问题。
提前致谢!