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:
- Conciseness: Uses
flatMapto handle both processing each contact and expanding into individual number objects in one pass, eliminating the need for intermediate arrays and manualpushcalls. - Efficiency: Deduplicating with
Setruns in O(n) time, which is way faster than your originalfindIndexmethod (O(n²) complexity) — this makes a big difference with larger contact lists. - 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
相关产品推荐
相关产品推荐

