Merge Array Objects and Remove Duplicates Based on Common Key

Abstract: Merge array objects and remove duplicates based on a common key using JavaScript Map for efficient deduplication.

Created: 2026-07-31 by
To merge array objects and remove duplicates based on a common key in JavaScript, you can utilize the reduce() method combined with a Map object. This approach iterates through the original array once, using the specified key as the unique identifier for each entry in the map. When an object with that key already exists, you can choose to either skip it to preserve uniqueness or update its properties to merge data. This technique is highly efficient, offering linear time complexity relative to the number of items, which makes it suitable for large datasets where performance matters.

Understanding the Problem Structure

When working with arrays of objects, developers often encounter scenarios where multiple entries share the same identifier but contain different or overlapping data. For instance, you might have a list of user profiles where the id field is repeated because the data comes from multiple sources. The goal is to consolidate these into a single array where each id appears only once. This process involves two distinct steps: identifying the duplicate keys and deciding how to handle the conflicting or redundant information. In many cases, simply removing duplicates is not enough; you may need to merge specific fields. For example, if one object has a name and another has an email for the same user, you want a single object containing both. However, if the context implies strict deduplication without merging additional fields, the strategy shifts slightly to prioritizing the first occurrence or the last occurrence of the data. Understanding this distinction is crucial before implementing the solution.

The Map-Based Approach

The most robust way to handle this task is by leveraging the Map data structure available in modern JavaScript environments. A Map allows you to store key-value pairs where the key is unique. By iterating over your array and setting each object's key property as the map key, you automatically enforce uniqueness. If a key already exists, the new value will overwrite the old one, or you can implement logic to skip the insertion entirely. Here is a typical implementation pattern:
const mergeAndDeduplicate = (arr, key) => {
  const map = new Map();
  
  arr.forEach(item => {
    // Only add if the key doesn't exist yet, preserving the first occurrence
    if (!map.has(item[key])) {
      map.set(item[key], item);
    }
  });
  
  return Array.from(map.values());
};
This code snippet demonstrates how to keep the first instance of each unique key. If you prefer to keep the last instance, you would simply remove the if condition, allowing the map.set operation to always overwrite previous entries for the same key. This method is clean, readable, and avoids the nested loops that lead to poor performance in larger applications.

Merging Properties Instead of Just Deduplicating

Sometimes, "merging" implies combining the properties of two objects rather than just selecting one. In such cases, you can extend the previous logic by using Object.assign() or the spread operator within the loop. This allows you to retain data from both objects when they share a key.
const mergeObjects = (arr, key) => {
  const map = new Map();
  
  arr.forEach(item => {
    const existing = map.get(item[key]);
    if (existing) {
      // Merge the existing object with the current one
      Object.assign(existing, item);
    } else {
      // Create a shallow copy to avoid mutating the original reference
      map.set(item[key], { ...item });
    }
  });
  
  return Array.from(map.values());
};

This approach ensures that no data is lost during the deduplication process. It is particularly useful when aggregating metrics or combining partial records from different API responses. Note that Object.assign performs a shallow merge, meaning nested objects are copied by reference. For deep merging, you would need a library like Lodash or a custom recursive function.

Performance Considerations

Using a Map provides O(n) time complexity, where n is the length of the array. This is significantly better than the naive approach of using filter() with findIndex(), which results in O(n²) complexity due to nested iterations. For small arrays, the difference is negligible, but for thousands of records, the Map approach will execute much faster. Additionally, Map maintains insertion order, which can be beneficial if the order of elements in the resulting array matters to your application logic.

Alternative Methods

While the Map approach is recommended, other methods exist. You can use reduce() to build a new array directly, checking for existence using some(). However, this also results in O(n²) complexity. Another alternative is converting the array to a JSON string, using a Set to filter duplicates, and then parsing back, but this is generally discouraged due to performance overhead and potential issues with property ordering or type coercion. For those who frequently work with complex data transformations, integrating utility libraries can simplify syntax. Libraries like Lodash provide functions such as uniqBy() which abstract away the underlying logic. However, understanding the native JavaScript implementation remains important for debugging and optimizing custom solutions without external dependencies. If you are dealing with asynchronous data fetching before merging, consider reading our guide on handling promises correctly. See Push elements to array returned by a promise for details on managing async flows that feed into these merging functions.

Frequently Asked Questions

Does the Map approach preserve the original order?

Yes, JavaScript Maps maintain insertion order. This means the first occurrence of each unique key will appear in the final array at the position it was first encountered, ensuring predictable output order.

How do I handle case-sensitive keys?

If your keys are strings and case sensitivity is an issue, normalize them before using them as map keys. For example, convert all keys to lowercase using item[key].toLowerCase() when calling map.has() and map.set().

Can I merge deeply nested objects?

No, Object.assign() only performs shallow merges. Nested objects will be replaced entirely rather than merged. To achieve deep merging, you must use a dedicated library or write a recursive function that traverses both objects.

What if my array contains null or undefined values?

You should add a check at the beginning of your iteration to skip invalid entries. Use if (!item || !item[key]) continue; to prevent errors when trying to access properties on non-existent objects.

Is there a built-in method for this in older browsers?

Map is supported in all modern browsers and Node.js versions. For very old environments like Internet Explorer 11, you would need to use a polyfill or fall back to using plain objects as dictionaries, though this has limitations with non-string keys.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More