2 回答
TA贡献1876条经验 获得超7个赞
我在这里假设“Top_Section”总是在sections 数组的第一个位置。
我还假设只有两种优先级类型:“Top_Section”和“Bottom_Section”
let list = [{
id: 'field1',
sections: [{
name: 'Top_Section',
priority: 3
},
{
name: 'Bottom_Section',
priority: 3
}
]
},
{
id: 'field2',
sections: [{
name: 'Top_Section',
priority: 2
},
{
name: 'Bottom_Section',
priority: 4
}
]
},
{
id: 'field3',
sections: [{
name: 'Top_Section',
priority: 1
},
{
name: 'Bottom_Section',
priority: 1
}
]
},
{
id: 'field4',
sections: [{
name: 'Top_Section',
priority: 4
},
{
name: 'Bottom_Section',
priority: 2
}
]
}
];
function sortBy(priorityName) {
let priorityPosition = (priorityName == 'Top_Section') ? 0 : 1;
return (a, b) => {
return a['sections'][priorityPosition].priority - b['sections'][priorityPosition].priority;
}
}
console.log( list.sort(sortBy('Top_Section')) );
TA贡献1833条经验 获得超4个赞
让我们创建一个比较器
function compare(a, b) {
var sumA = 0;
var sumB = 0;
for (var section of a.sections) sumA += section.priority;
for (var section of b.sections) sumB += seciton.priority;
return sumB - sumA;
}
arr.sort(compare);
如果第一个参数较大,比较器返回正数,如果第二个参数较大,则比较器返回负数,如果它们相等,则返回 0。我假设优先级总和的数值越小,项目越大。
添加回答
举报