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

如何用最简方法去除JavaScript数组中的重复元素?

JavaScript数组简洁去重方案

针对你的数组去重需求,这里有两种极简的实现方式,一行代码就能搞定:

  • 使用Set + 扩展运算符
    利用ES6的Set数据结构自动过滤重复值的特性,再通过扩展运算符将集合转回数组:

    const colors = ['red','blue','green','yellow','red','blue'];
    const uniqueColors = [...new Set(colors)];
    // 输出结果:['red','blue','green','yellow']
    
  • 使用Array.from + Set
    若更习惯用Array.from方法转换集合,也可以这样写:

    const colors = ['red','blue','green','yellow','red','blue'];
    const uniqueColors = Array.from(new Set(colors));
    // 结果同样是去重后的数组
    

这两种方案都是现代JavaScript里最简洁的去重方式,兼容性覆盖绝大多数现代浏览器和Node.js环境,完全不需要复杂的循环或判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:05:19