如何优化基于数组匹配表头合并表格列的低效JS代码
列合并代码优化方案
优化核心
- 移除不安全、不符合开发规范的
eval逻辑,全部使用原生数组操作实现,避免不必要的性能损耗 - 支持
CriteriaMatchArray传入多个匹配关键词,仅需一次运行即可完成所有匹配列的合并,无需反复输入执行 - 仅需两次遍历(1次表头预处理、1次数据行遍历)即可完成全部计算,无冗余遍历,性能提升明显
优化后完整可运行代码
<!DOCTYPE html> <html> <body> <script> const table = [ ["Sl.no","fruits 1", "fruits 2", "fruits 3", "fruits 4", "fruits 5", "vegetables 1", "vegetables 2"], ["1","banana", "apple", "orange", "", "", "carrot", "cabbage"], ["2","watermelon", "apple", "orange", "", "", "beans", ""] ]; // 可同时传入多个匹配关键词,无需重复运行 const CriteriaMatchArray = ["fruits", "vegetables"]; // 预处理表头生成合并规则 const header = table[0]; const matchGroups = {}; const outputRule = []; const processedKeys = new Set(); for (let colIndex = 0; colIndex < header.length; colIndex++) { const headerName = header[colIndex]; let matchedKey = null; for (const key of CriteriaMatchArray) { if (headerName.includes(key)) { matchedKey = key; break; } } if (!matchedKey) { outputRule.push(colIndex); continue; } if (!matchGroups[matchedKey]) matchGroups[matchedKey] = []; matchGroups[matchedKey].push(colIndex); if (!processedKeys.has(matchedKey)) { processedKeys.add(matchedKey); outputRule.push(matchedKey); } } // 遍历生成结果 const result = table.map(row => { return outputRule.map(rule => { if (typeof rule === 'number') return row[rule]; return matchGroups[rule].map(colIndex => row[colIndex]).join('#'); }) }); // 页面输出结果 document.write('<pre>给定表格:' + JSON.stringify(table, null, 4) + '</pre>'); document.write('<pre>合并后结果:' + JSON.stringify(result, null, 4) + '</pre>'); </script> </body> </html>
效果说明
代码逻辑与原需求完全对齐:表头包含匹配关键词的所有列会按顺序用#拼接为一列,位置在该关键词首次匹配到的列的位置,未匹配的列保持原有顺序不变。可直接修改CriteriaMatchArray数组添加多个匹配项,一次运行即可得到最终结果。
内容的提问来源于stack exchange,提问作者user16731842
相关产品推荐
相关产品推荐

