自定义multisort多排序函数无法返回预期排序结果的原因排查
问题原因分析与修复方案
哦,我一眼就发现问题所在了——你的multisort函数里用了o.property来获取排序字段,但你定义的sortBy数组里的键名是prop,不是property!这就导致每次排序比较时,a[property]和b[property]都是undefined,最终比较结果始终为0,排序逻辑完全没生效。
具体细节拆解
当你在sortBy.forEach里执行const property = o.property;时,你的sortBy数组元素是{ prop:'grade', direction: -1 }这类结构,o.property会直接返回undefined。此时a[undefined]和b[undefined]也都是undefined,在比较时:
undefined > undefined结果为falseundefined < undefined结果也为false
所以result始终保持初始值0,Array.sort()会认为所有元素的顺序都不需要调整,自然返回和原克隆数组一模一样的结果。
修复代码(两种方案任选其一)
方案1:修改multisort函数中的字段名
让函数里的字段名和sortBy数组的键名匹配:
function multisort(data, sortBy) { const dataClone = JSON.parse(JSON.stringify(data)); return dataClone.sort((a, b) => { let result = 0; sortBy.forEach(o => { if (result !== 0) return; // 将o.property改为o.prop,和sortBy里的键名统一 const property = o.prop; result = o.direction * ( a[property] > b[property] ? 1 : (a[property] < b[property] ? -1 : 0) ); }); return result; }); }
方案2:修改sortBy数组的键名
让排序规则的键名和函数里的取值逻辑匹配:
const sortBy = [ { property:'grade', direction: -1 }, { property:'lastName', direction: 1 } ];
修复后的预期效果
修正后,sortedStudents会按照你预期的规则排序:先按grade降序(12→11→10),再按lastName升序(Appletree在前,Peachtree在后),最终输出的排序结果应该是:
[ { firstName: 'John', lastName: 'Appletree', grade: 12 }, { firstName: 'Shooter', lastName: 'Appletree', grade: 12 }, { firstName: 'Peter', lastName: 'Peachtree', grade: 12 }, { firstName: 'Kim', lastName: 'Appletree', grade: 11 }, { firstName: 'Mighty', lastName: 'Peachtree', grade: 10 } ]
另外提一句:你在函数里用JSON.parse(JSON.stringify(data))做深克隆是正确的,这样原数组students不会被排序逻辑修改,这部分的处理没问题~
内容的提问来源于stack exchange,提问作者knot22
相关产品推荐
相关产品推荐

