You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组合并函数极致优化挑战

优化JavaScript合并去重函数至最佳性能

原函数存在的问题

  • 参数数量固定为5个,无法灵活处理任意数量的数组输入
  • 使用indexOf检查元素是否重复,每次检查的时间复杂度为O(k)(k为结果数组长度),整体时间复杂度达O(nk),数据量大时性能极差
  • 使用var声明变量存在变量提升风险,代码安全性不足

优化方案及实现

方案1:基础高性能版(函数声明形式)

利用Set的O(1)时间复杂度去重特性,搭配剩余参数实现任意数组数量支持:

function merge(...arrays) {
  const uniqueSet = new Set();
  // 遍历所有输入数组
  for (const array of arrays) {
    // 遍历当前数组的每个元素
    for (const item of array) {
      uniqueSet.add(item);
    }
  }
  // 将Set转换为数组返回
  return Array.from(uniqueSet);
}

方案2:极简高效版(箭头函数形式,更节省内存)

利用数组展开与Set的特性,用一行代码实现,同时保证性能:

// 兼容ES2019+(支持flat方法)
const merge = (...arrays) => Array.from(new Set(arrays.flat()));

// 兼容旧环境版本(用concat替代flat)
const merge = (...arrays) => Array.from(new Set([].concat(...arrays)));

优化效果说明

  • 扩展性:通过剩余参数...arrays支持任意数量的数组输入,不再受固定参数限制
  • 性能:时间复杂度从原有的O(nk)降至O(n)(n为所有数组的元素总数),大数据量下性能提升显著
  • 内存效率:Set存储唯一值的方式比数组+indexOf的组合更节省内存,且操作更高效
  • 代码安全性:使用const/let替代var,避免变量提升导致的潜在问题

测试验证

使用原测试代码验证,结果与原函数一致,但性能更优:

const x = ['hi','hello','hey']
const y = ['apple','banana','orange']
const z = ['hie','helloe','heye']
const w = ['applei','bananai','orangei']
const e = ['hio','helloo','heyo']

console.log(merge(x,y,z,w,e));
// 输出:["hi","hello","hey","apple","banana","orange","hie","helloe","heye","applei","bananai","orangei","hio","helloo","heyo"]

内容的提问来源于stack exchange,提问作者Plain_69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 01:11:32