上一篇
【2025年8月消息】随着ECMAScript 2025正式发布,JavaScript新增了Array.prototype.unique()
实验性提案(目前需Babel转译),但日常开发中我们仍需掌握这些经得起考验的去重技巧——
const arr = [1, 2, 2, 'apple', 'apple']; const uniqueArr = [...new Set(arr)]; // [1, 2, 'apple']
特点:代码最简洁,但无法区分1
和'1'
const arr = ['a', 'b', 'a', NaN]; const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index); // ['a', 'b', NaN]
注意:无法去除重复的NaN
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'}]
说明:对象元素需特殊处理
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}]
方法 | 典型应用场景 | 示例 |
---|---|---|
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: [...] }
混合类型去重:
const mixArr = [1, '1', new String('1')]; const strictUnique = arr => [...new Set(arr.map(item => JSON.stringify(item)))].map(JSON.parse);
大数据量优化:
// 使用Int32Array处理百万级数字去重 const bigArr = new Int32Array([1,2,2,3]); const uniqueBigArr = [...new Int32Array(new Set(bigArr))];
最后建议:简单场景用Set
,特殊类型用reduce
,超大数据考虑类型化数组,记得在实际项目中做好性能测试,2025年的Chrome V8引擎对Set
的优化又有了新突破哦!
本文由 恭羡丽 于2025-08-02发表在【云服务器提供商】,文中图片由(恭羡丽)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/517238.html
发表评论