如何对复杂结构的卡片对象数组进行自定义排序?
卡片数组复杂排序实现
问题场景
现有如下卡片对象数组:
const cards = [ { type: { method: 'listen' }, reference: ['destroyed', 'word 2'] }, { type: { method: 'synonym' }, reference: ['destroyed'] }, { type: { method: 'listen' }, reference: ['destroyed'] }, { type: { method: 'dictate' }, reference: ['destroyed'] } ]
需要按照以下规则排序:
listen类型的卡片排在最前面- 同是
listen类型的卡片,reference.length越小越靠前 - 其他类型的卡片排在其后
dictate类型的卡片排在最后
目前已实现部分排序逻辑,需要完善完整的排序函数:
cards.sort(compare); function compare(a, b) { if(a.type.method == 'listen') return a.reference.length - b.reference.length; ... }
解决方案
通过给不同类型的卡片分配优先级权重,可以实现多规则的排序需求,具体实现代码如下:
const cards = [ { type: { method: 'listen' }, reference: ['destroyed', 'word 2'] }, { type: { method: 'synonym' }, reference: ['destroyed'] }, { type: { method: 'listen' }, reference: ['destroyed'] }, { type: { method: 'dictate' }, reference: ['destroyed'] } ] function compare(a, b) { // 定义各类型的优先级权重,数值越大优先级越高 const getPriority = (method) => { switch(method) { case 'listen': return 2; case 'dictate': return 0; default: return 1; // 匹配synonym等其他类型 } } const priorityA = getPriority(a.type.method); const priorityB = getPriority(b.type.method); // 先比较优先级,优先级高的排前面 if (priorityA !== priorityB) { return priorityB - priorityA; } // 若都是listen类型,按reference长度升序排列(短的在前) if (a.type.method === 'listen') { return a.reference.length - b.reference.length; } // 同优先级的非listen类型,保持原有相对顺序(可根据需求修改此处规则) return 0; } cards.sort(compare); console.log(cards);
逻辑说明
- 优先级分配:用
getPriority函数给不同method赋值权重,listen权重最高(2),普通类型(如synonym)权重1,dictate权重最低(0)。 - 优先级比较:优先对比两个卡片的优先级,权重高的排前面(通过
priorityB - priorityA实现降序)。 - listen类型内部排序:当两个卡片都是
listen类型时,通过a.reference.length - b.reference.length实现升序,即长度小的在前。 - 同优先级其他类型:相同优先级的非listen类型,返回0保持原有相对顺序,若需要其他排序规则可在此处补充。
内容的提问来源于stack exchange,提问作者Sara Ree
相关产品推荐
相关产品推荐

