请问以下js排序代码,如何优化呢?
const sort_fun = {
名称: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.pinyin[0] < b.pinyin[0] ? 1 : -1
}
return a.pinyin[0] < b.pinyin[0] ? -1 : 1
}),
类型: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.suffix < b.suffix ? 1 : -1
}
return a.suffix < b.suffix ? -1 : 1
}),
大小: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.bytes < b.bytes ? 1 : -1
}
return a.bytes < b.bytes ? -1 : 1
}),
时间: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.timestamp.mtime < b.timestamp.mtime ? 1 : -1
}
return a.timestamp.mtime < b.timestamp.mtime ? -1 : 1
}),
}
因为 a.pinyin[0]
的原因,我不知道怎么用 a[..]
的方式简化代码
谢谢
回复
1个回答

test
2024-07-01
将原有的四个独立的排序函数合并为一个通用的 sortData 方法,通过传入不同的参数来适应不同的属性和排序方向。
const sortFun = {
// 通用排序方法
sortData: function(curr_data, prop, is_desc) {
// 根据 is_desc 的值确定排序的方向
const direction = is_desc ? 1 : -1;
// 使用 sort 方法对 curr_data.children 数组进行排序
// 注意这里使用了箭头函数
return curr_data.children.sort((a, b) => {
// 通过 prop 参数指定的属性名获取 a 和 b 的属性值
// 如果属性是嵌套的,例如 'timestamp.mtime',这里会递归地访问到这个深层属性
const aValue = prop.split('.').reduce((o, i) => o[i], a);
const bValue = prop.split('.').reduce((o, i) => o[i], b);
// 比较两个属性值
if (aValue < bValue) {
// 如果 a 的属性值小于 b 的属性值,则返回负数(升序)或正数(降序),根据 direction 的值
return direction * -1;
}
if (aValue > bValue) {
// 如果 a 的属性值大于 b 的属性值,则返回正数(升序)或负数(降序),根据 direction 的值
return direction * 1;
}
// 如果两个属性值相等,则返回 0,表示它们在排序中视为相等
return 0;
});
},
};
// 使用示例:
// 调用 sortData 方法进行排序
// 第一个参数是当前要排序的数据
// 第二个参数是要基于哪个属性进行排序
// 第三个参数是是否为降序排序
sortFun.sortData(curr_data, 'pinyin', false); // 升序排序 pinyin 属性
sortFun.sortData(curr_data, 'suffix', true); // 降序排序 suffix 属性
sortFun.sortData(curr_data, 'bytes', false); // 升序排序 bytes 属性
sortFun.sortData(curr_data, 'timestamp.mtime', true); // 降序排序 timestamp.mtime 属性
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容