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

JavaScript嵌套数组去重并转换结构的代码优化咨询

Great question! Your original code gets the job done, but we can streamline it to be more concise, efficient, and readable using modern JavaScript features. Here's an improved version:

const contacts = [
  {givenName: "Name 1", phoneNumbers: [ {label: "mobile", id: "5", number: "097 726 94 36"}, {label: "other", id: "558", number: "0977269436"}, {label: "other", id: "559", number: "0977269436"} ]},
  {givenName: "Name 2", phoneNumbers: [ {label: "mobile", id: "5", number: "0968234838"}, {label: "other", id: "558", number: "0966766555"}, {label: "other", id: "559", number: "0966766555"} ]},
  {givenName: "Name 3", phoneNumbers: [ {label: "other", id: "558", number: "0965777238"}, {label: "other", id: "559", number: "0965777238"} ]},
];

const processedContacts = contacts.flatMap(contact => {
  // Step 1: Filter valid numbers (length ≤ 11, matching your original logic)
  const validNumbers = contact.phoneNumbers
    .map(phone => phone.number)
    .filter(num => num.length <= 11); // Adjust to <=10 if that's your exact requirement
  
  // Step 2: Remove duplicates efficiently with a Set
  const uniqueValidNumbers = [...new Set(validNumbers)];
  
  // Step 3: Map to the final object format
  return uniqueValidNumbers.map(number => ({
    givenName: contact.givenName,
    phoneNumbers: number
  }));
});

console.log(processedContacts);

Why this approach is better:

  1. Conciseness: Uses flatMap to handle both processing each contact and expanding into individual number objects in one pass, eliminating the need for intermediate arrays and manual push calls.
  2. Efficiency: Deduplicating with Set runs in O(n) time, which is way faster than your original findIndex method (O(n²) complexity) — this makes a big difference with larger contact lists.
  3. Readability: Each step is clearly separated and self-documenting, so it’s easier to tweak later (like adjusting the length filter or adding new processing rules).

Quick note:

I used num.length <=11 to match your original code’s behavior (you excluded numbers longer than 11 characters). If your actual requirement is strictly ≤10 digits, just update that condition to num.length <=10.

内容的提问来源于stack exchange,提问作者Linh Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:52:45