You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从对象数组中去除重复邮箱对象但保留空邮箱对象?

解决邮箱去重但保留空邮箱对象的问题

你可以修改过滤逻辑,区分非空邮箱和空邮箱两种情况:

  • 对于邮箱非空的对象,只保留第一次出现的实例
  • 对于邮箱为空的对象,全部保留

修改后的代码如下:

const uniqueContacts = arr.filter((v, i, a) => {
  // 邮箱为空时直接保留
  if (v.email === '') return true;
  // 邮箱非空时,仅保留首次出现的对象
  return a.findIndex(v2 => v2.email === v.email) === i;
});

测试验证

用你提供的示例数组测试:

var arr = [
  { name: '1', city: 'lagos', email: 'second@gmail.com' },
  { name: '2', city: 'abuja', email: 'second@gmail.com' },
  { name: '3', city: 'ibadan', email: '' },
  { name: '4', city: 'kano', email: '' },
];

const uniqueContacts = arr.filter((v, i, a) => {
  if (v.email === '') return true;
  return a.findIndex(v2 => v2.email === v.email) === i;
});

console.log(uniqueContacts);

输出结果会保留name:1(移除重复的name:2),同时完整保留name:3和name:4,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Shina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:34:53