JavaScript数组按属性去重的核心是提取属性值作唯一标识并过滤重复项,常用filter+findIndex(兼容性好)、Map(O(n)性能优)和reduce(语义清晰)三种方法,并需特殊处理null/undefined/NaN。

在 JavaScript 中,根据对象的某个属性对数组去重,核心思路是:**提取该属性值作为唯一标识,过滤掉重复标识对应的后续元素**。常用且简洁的方法是用 filter() 配合 findIndex() 或使用 Map 记录已出现的属性值。
用 filter + findIndex 保留首次出现的项
这是最直观、兼容性好的方式。遍历数组时,检查当前元素的指定属性值,在原数组中第一次出现的位置是否就是当前索引。
- 适用于大多数场景,代码易读,支持 IE9+
- 假设数组为
list,要去重的属性是id:
const uniqueList = list.filter((item, index) => list.findIndex(obj => obj.id === item.id) === index );
如果属性是嵌套的(如 user.profile.name),把比较逻辑写清楚即可:
list.filter((item, index) => list.findIndex(obj => obj.user?.profile?.name === item.user?.profile?.name) === index );
用 Map 实现一次遍历(性能更优)
当数组很大时,filter + findIndex 时间复杂度是 O(n²),而用 Map 可降到 O(n) ——边遍历边记录已见的属性值,跳过重复项。
立即学习“Java免费学习笔记(深入)”;
- 适合大数据量或对性能敏感的场景
- 注意:需确保属性值是字符串、数字或 symbol;若为对象/数组,需先转成唯一字符串(如 JSON.stringify)
const seen = new Map();
const uniqueList = list.filter(item => {
const key = item.id; // 替换为你想依据的属性名
if (seen.has(key)) return false;
seen.set(key, true);
return true;
});
用 reduce 构建唯一集合(语义清晰)
借助 reduce 累积一个不含重复项的新数组,逻辑明确,也方便扩展(比如合并重复项的其他字段)。
const uniqueList = list.reduce((acc, current) => {
const exists = acc.some(item => item.id === current.id);
return exists ? acc : [...acc, current];
}, []);
如果希望更高效,可配合 Map 或用 find 替代 some(避免每次遍历整个 acc):
const uniqueList = list.reduce((acc, current) => {
if (!acc.find(item => item.id === current.id)) {
acc.push(current);
}
return acc;
}, []);
处理特殊值:null / undefined / NaN
如果去重属性可能为 null、undefined 或 NaN,要注意相等判断行为:
-
NaN === NaN是 false,所以直接用===会误判为不重复 - 建议统一转成字符串再比较(
String(item.prop)),或用Object.is(a, b)判断(它认为Object.is(NaN, NaN) === true)
// 安全比较 NaN 和其他值 const key = Object.is(item.id, NaN) ? 'NaN' : item.id;


















