如何实现数组排序时将名为Protein的元素固定排在最顶部
实现方案
你只需要在现有排序分组逻辑的最前面,新增一层针对Protein元素的过滤提取即可,改动后的代码如下:
public getFilteredProbeGroups(): ipGroup[] { return this.probesSorting(this.filteredProbeGroups, this.selectedProbeGroupIds); } public probesSorting(probes: any[], selectedProbes: number[]): any[] { // 提取所有name为Protein的元素,优先级最高 const proteinItem = probes.filter(item => item.name === 'Protein'); // 剩余元素走原有排序逻辑 const otherItems = probes.filter(item => item.name !== 'Protein'); const compareLoc = (a, b) => a.name.localeCompare(b.name); // 选中项按名称排序 const sortedSelected = otherItems.filter(d => selectedProbes.includes(d.id || d.probeGroupId)).sort(compareLoc); // 未选中项按名称排序 const sortedUnselected = otherItems.filter(d => !selectedProbes.includes(d.id || d.probeGroupId)).sort(compareLoc); // 按优先级拼接结果:Protein固定在最前 > 选中元素 > 未选中元素 return [...proteinItem, ...sortedSelected, ...sortedUnselected]; }
改动说明
- 优先级最高的
Protein元素会固定排列在数组最顶部,原有选中项优先、同组按名称字典序排序的逻辑完全保留 - 删掉了原代码中冗余的第一层sort操作,无需提前排序即可通过分组拼接实现需求,性能更优
- 若存在多个名为
Protein的元素,可在提取时添加排序逻辑:const proteinItem = probes.filter(item => item.name === 'Protein').sort(compareLoc),保证多个Protein元素之间也按字典序排列
内容的提问来源于stack exchange,提问作者Aw KingOftheworld
相关产品推荐
相关产品推荐

