最高效去重用 set,适用于原始类型数组;对象数组按字段去重推荐 map 缓存标识;深层结构可封装 uniqueby 函数支持动态 key;需避开 indexof、json.stringify 等坑点。

直接用 Set 是最高效的方式,尤其适合接口返回的原始类型数组(如 ID 列表、用户名、状态码等)。
基础去重:一行搞定,适用于字符串/数字/布尔值
接口返回的扁平数组,比如 [1, 2, 2, "3", "3", null, null],可直接用:
这个方法自动保留首次出现顺序,正确处理 null、undefined、NaN,时间复杂度为 O(n),性能远超循环遍历。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
对象数组按字段去重:用 Map 缓存关键标识
当接口返回的是对象列表,例如用户列表 [{id: 1, name: "张三"}, {id: 1, name: "李四"}],需按 id 去重:
const map = new Map();
return !map.has(item.id) && map.set(item.id, true);
});
更推荐拆开写,逻辑清晰且可复用:
const seen = new Map();const uniqueUsers = apiResponse.filter(item => {
if (seen.has(item.id)) return false;
seen.set(item.id, true);
return true;
});
深层结构或动态字段去重:自定义 key 提取函数
如果去重依据不是固定字段(比如有时用 id,有时用 email + role 组合),可封装通用函数:
const seen = new Map();
return arr.filter(item => {
const key = typeof getKey === 'function' ? getKey(item) : item[getKey];
if (seen.has(key)) return false;
seen.set(key, true);
return true;
});
}
// 使用示例:
uniqueBy(users, 'id');
uniqueBy(items, item => `${item.category}-${item.version}`);
注意避坑的几个点
- 别用
filter + indexOf处理对象数组——indexOf对对象永远返回-1,去重失效 - 避免用
JSON.stringify当 key——对象属性顺序不一致会导致误判,且性能差 - 旧环境(如 IE)不支持
Set或Map,需用 Babel 转译或降级为对象键模拟(仅限字符串 key) - 大数据量(>10 万条)时,
Set和Map仍是首选,实测比filter + indexOf快 50 倍以上
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










