The art of combining arrays of objects while eliminating duplicates

I am in need of a solution to compare two object arrays, remove duplicates, and merge them into a single array. Although I am relatively new to javascript/Typescript, I have come across some blogs suggesting the use of Map, reduce, and filter methods for this task. Is that the most effective approach?

Alternatively, I am curious if creating a map and utilizing Map.ContainsKey or Map.getValues() could also achieve the desired result.

In reality, the objects within the arrays are quite extensive, with multiple keys and hundreds of records in each array.

   [
    {
        Name: Roger
        Country : Spain
    },
    {
        Name: Tiger
        Counry : USA
    },
    {
        Name: Micheal
        Country: USA
    },
]


[
    {
        Name: Sachin
        Country : India
    },
    {
        Name: Roger
        Counry : Spain
    },
]

output 

[
    {
        Name: Roger
        Country : Spain
    },
    {
        Name: Tiger
        Counry : USA
    },
    {
        Name: Micheal
        Country: USA
    },
    {
        Name: Sachin
        Country : India
    }
]

Answer №1

A possible solution is to use a hash table with the desired values as keys and then add elements that do not have a flag in the hash table.

var array1 = [{ Name: 'Roger', Country: 'Spain' }, { Name: 'Tiger', Counry: 'USA' }, { Name: 'Micheal', Country: 'USA' }],
    array2 = [{ Name: 'sachin', Country: 'India' }, { Name: 'Roger', Country: 'Spain' }],
    hash = Object.create(null),
    result = [array1, array2].reduce(function (r, a) {
        a.forEach(function (o) {
            var key = ['Name', 'Country'].map(k => o[k]).join('|');
            if (!hash[key]) {
                r.push(o);
                hash[key] = true;
            }
        });
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Here is an efficient ES6 solution that utilizes the map() and filter() methods.

Combining two arrays of objects while eliminating duplicate objects

let arr1 =    [
    {
        Name: 'Roger',
        Country : 'spain'
    },
    {
        Name:'Tiger',
        Country : 'USA'
    },
    {
        Name: 'Micheal',
        Country: 'USA'
    },
];
let arr2 = [
    {
        Name: 'sachin',
        Country : 'India'
    },
    {
        Name:'Roger',
        Country : 'Spain'
    },
]
let arr3 = [...arr1, ...arr2]

function mergeUniqueArray(arr, comp) {

  let unique = arr
    .map(item => item[comp])

     // store the keys of the unique objects
    .map((item, i, final) => final.indexOf(item) === i && i)

    // eliminate the duplicate keys & store unique objects
    .filter(item => arr[item]).map(item => arr[item]);
   return unique;
}

console.log(mergeUniqueArray(arr3,'Name'));

Answer №3

Check out this potential solution:

// Step 1: Merge the two arrays together.
const mergedItems = itemsList1.concat(itemsList2);

// Step 2: Transform the merged array into key/value pairs.
const keyValuePairs = mergedItems.map(item => [`${item.Name}:${item.Country}`, item]);

// Step 3: Utilize a Map to remove duplicates.
const mapOfItems = new Map(keyValuePairs);

// Step 4: Convert the unique values back into an array.
const finalResult = [...mapOfItems.values()];

Here are some important points about this method:

  1. When combining arrays in step 1, the order matters! Items from itemsList2 will take precedence over those from itemsList1. This is crucial for situations where objects have additional properties beyond what's being compared.
  2. If there's a possibility of collisions due to special characters like : in name/country combinations, consider modifying how you construct the entry keys.
  3. The use of a Map with a hashtable implementation ensures efficient duplicate removal.
  4. Since Map maintains input sequence, the resulting array will mirror the order of elements in the merged array while eliminating duplicates. To change the output order, sorting may be necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the parent div overflows, the child div remains hidden within the boundaries of the parent div

<section class="margin-top-30"> <div class="row" style="position: relative;"> <div class="col-sm-4"> <div class="lightbgblock" style="overflow-x:visible;overflow-y:scroll;"> ...

How to transform an array into a collection of objects using React

In my React project, I encountered the following data structure (object of objects with keys): const listItems = { 1:{ id: 1, depth: 0, children: [2,5] }, 2:{ id: 2, depth: 1, children: [3,4], parentIndex: 1, disable ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

The AJAX request to the REST service is failing to trigger the success function in the AJAX call

Struggling with some issues related to AJAX, specifically when calling a Java REST server that I've developed. While I am relatively new to AJAX, I have put in quite a bit of effort searching for solutions. The problem arises when making a call from a ...

Prevent further clicking on a button in a custom Drupal module after it has been clicked three times

I'm new to using Drupal and have created a custom module similar to webform. In my module page, I have two submit buttons and 2 textboxes as shown below: function contact_request($form, &$form_state) { $form ['info'] =array( &ap ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

The Cy.visit() function in Cypress times out and bypasses tests specifically when navigating to a VueJS web application

Having trouble with the Cypress cy.visit() function timing out and aborting tests on a VueJS Web Application? It seems to work fine when opening other non-VueJS sites. Below is my basic configuration setup: [package.json] "dependencies": { "cypres ...

Troubleshooting Axios NPM connectivity issue in Express.js

I have created an express.js route with the following code snippet: - const path = require("path"); const express = require("express"); const hbs = require("hbs"); const weather = require("./weather"); const app = express(); app.get("/weather", (req, ...

What is the best way to show inline icons within menu items?

Issue Upon selecting an option from the menu, I encounter a problem where the icon (represented by a question mark inside a speech bubble) appears on a different line than the text ("Question"). Fig. 1. Display of menu after selection with the icon and t ...

The jQuery $.change function is not functioning properly when used with a cloned select element

In my table, there is a button that allows you to add a new row by cloning the last one. Each row contains a <select> with a different name (0-9), all having the class .variable_priority. When clicking the button, the row clones successfully and the ...

Leveraging numpy arrays for handling both integer values and arrays as input

As a Matlab user transitioning into Python, I attempted to code a minimal version of the de2bi function in Python. This function converts a decimal number into binary with the right-most significant bit first. However, I encountered some confusion when wor ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...

The value of req.body.name cannot be determined in Express using Node.js

I want to implement a like/dislike feature on my website using HTML and JavaScript. Here is the code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> <input type="submit" name="vote" value= ...

Determining the name of a key in a JSON object using PHP

There is a JSON structure where the description serves as a key for an array of JSON elements. For instance: { 'groups' : array[ 0 => { 'id' : '1' 'free gif ...

Tips for verifying that input is provided in a text field when the checkbox is marked

Can someone help me with validating a form where the user must enter data in a text field if they check a checkbox? I have JavaScript code for checkbox validation, but need assistance with text field validation. Thank you! $(document).ready(function () ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...

ReferenceError: source is not defined in Gulp with Browserify

I encountered a strange error while working on my project. The error message I received is as follows: $ gulp browserify [01:21:03] Using gulpfile F:\CSC Assignments\FinalProject\HotelProject\gulpfile.js [01:21:03] Starting 'bro ...

Using array for Json deserialization

Having difficulties with json deserialization Here is the JSON string: { "id": "1", "marketId": "1", "userId": "2", "svisorId": "1", "orders": "[{\"Id\": 3, \"Count\": 1, \"Price\": 1000, \"Weight\": 1500 ...

How can you simultaneously send FormData and String Data using JQuery AJAX?

Is there a way to upload both file and input string data using FormData()? For example, I have several hidden input values that also need to be included in the server request. html, <form action="image.php" method="post" enctype="multipart/form-data"& ...

Best method for reusing a component in React?

Here is a simplified code featuring a reusable button component: import React from 'react' import styles from './Button.module.scss' const Button = (props) => { return ( <button type={props.type} className={styles.btn} onC ...