当前位置:首页 > 问答 > 正文

数组去重|js技巧:js数组如何去重?附常用数组方法

JS数组去重全攻略:2025年最新技巧与常用方法盘点

【2025年8月消息】随着ECMAScript 2025正式发布,JavaScript新增了Array.prototype.unique()实验性提案(目前需Babel转译),但日常开发中我们仍需掌握这些经得起考验的去重技巧——

7种实战验证的数组去重方案

Set数据结构法(ES6首选)

const arr = [1, 2, 2, 'apple', 'apple'];
const uniqueArr = [...new Set(arr)]; 
// [1, 2, 'apple']

特点:代码最简洁,但无法区分1'1'

filter+indexOf经典组合

const arr = ['a', 'b', 'a', NaN];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
// ['a', 'b', NaN] 

注意:无法去除重复的NaN

数组去重|js技巧:js数组如何去重?附常用数组方法

reduce一行代码版

const arr = [1, 1, 2, {name: 'Leo'}, {name: 'Leo'}];
const uniqueArr = arr.reduce((acc, cur) => acc.includes(cur) ? acc : [...acc, cur], []);
// [1, 2, {name: 'Leo'}, {name: 'Leo'}] 

说明:对象元素需特殊处理

对象键值法(兼容IE)

function unique(arr) {
  const obj = {};
  return arr.filter(item => 
    obj.hasOwnProperty(typeof item + item) ? 
    false : 
    (obj[typeof item + item] = true)
  );
}
// 可识别 1/'1' 和 NaN

针对对象数组的解决方案

const objArr = [{id:1}, {id:1}, {id:2}];
const uniqueObjArr = [...new Map(objArr.map(item => [item.id, item])).values()];
// [{id:1}, {id:2}]

2025年必备的12个数组方法

方法 典型应用场景 示例
flat() 多维数组扁平化 [1,[2]].flat()[1,2]
findLast() 倒序查找元素 [1,2,3].findLast(x=>x>1)3
at() 支持负数的安全访问 ['a','b'].at(-1)'b'
groupBy() 按条件分组(ES2025新增) 见下方代码示例

2025年新增groupBy示例

const inventory = [
  { name: 'asparagus', type: 'vegetables' },
  { name: 'bananas', type: 'fruit' }
];
inventory.groupBy(({ type }) => type);
// 结果:{ vegetables: [...], fruit: [...] }

特殊场景处理技巧

  1. 混合类型去重

    数组去重|js技巧:js数组如何去重?附常用数组方法

    const mixArr = [1, '1', new String('1')];
    const strictUnique = arr => [...new Set(arr.map(item => JSON.stringify(item)))].map(JSON.parse);
  2. 大数据量优化

    // 使用Int32Array处理百万级数字去重
    const bigArr = new Int32Array([1,2,2,3]);
    const uniqueBigArr = [...new Int32Array(new Set(bigArr))];

最后建议:简单场景用Set,特殊类型用reduce,超大数据考虑类型化数组,记得在实际项目中做好性能测试,2025年的Chrome V8引擎对Set的优化又有了新突破哦!

发表评论