JavaScript小技巧:数组去重的几种优雅写法
在日常开发中,数组去重是经常遇到的需求。除了传统的for循环加indexOf,ES6提供了更简洁的解法。
1. 最简洁:Set + 扩展运算符
const unique = arr => [...new Set(arr)];
// 示例:[1,2,2,3] => [1,2,3]
一行代码搞定,性能优异,适合多数场景。
2. 兼容对象:filter + findIndex
当数组包含对象时,Set无法直接去重(对象引用不同):
const uniqueObj = arr =>
arr.filter((item, index, self) =>
self.findIndex(t => t.id === item.id) === index
);
按id属性去重,灵活可控。
3. 性能优化:reduce + Map
对于大型数组,Map的查找效率更高:
const uniqueByMap = arr =>
[...arr.reduce((map, item) =>
map.set(item.id, item), new Map()).values()];
4. 实用技巧:过滤假值
const clean = arr => arr.filter(Boolean);
// [0, 1, false, 2, '', 3] => [1,2,3]
filter(Boolean)会移除所有假值(0, false, null, undefined, '')。
总结
- 简单类型用
Set - 对象数组根据业务选择合适的比较字段
- 追求性能考虑
Map
掌握这些技巧,代码质量立竿见影。