我如何使用desireOrder数组中的值对对象数组进行排序? 我希望按每个对象中的 type 键对数组对象进行排序。我希望所有 fruit 项目先显示,然后显示 drug 项目,然后显示 wheat 项目。等等,如果该功能是可重用的,那将是更可取的。
// This is the order I want myList sorted in by the object property type
let desiredOrder = ['fruit', 'drugs', 'wheat', 'candy', 'vegetable', 'dairy']
// Here is my list of objects
let myList = [
{
type: "fruit",
subType: "apple"
},
{
type: "vegetable",
subType: "carrot"
},
{
type: "fruit",
subType: "orange"
},
{
type: "dairy",
subType: "milk"
},
{
type: "wheat",
subType: "bread"
},
{
type: "vegetable",
subType: "lettuce"
},
{
type: "fruit",
subType: "mango"
},
{
type: "drugs",
subType: 'cocaine'
},
{
type: "vegetable",
subType: "spinach"
},
{
type: "candy",
subType: "chocolate"
},
{
type: "vegetable",
subType: "celery"
},
{
type: "fruit",
subType: "pineapple"
},
]
答案 0 :(得分:1)
功能
AKSWebservice
将首先根据数组中类型的顺序进行排序,如果类型相同,则按subType排序。
(a, b) => (desiredOrder.indexOf(a.type) - desiredOrder.indexOf(b.type)) || (a.subType > b.subType ? 1 : -1) || 0;
答案 1 :(得分:1)
您需要使用sort()
myList.sort((preItem, nextItem) =>
desiredOrder.indexOf(preItem.type) > desiredOrder.indexOf(nextItem.type) ? 1 : -1
);