Combine two arrays of objects while avoiding objects with duplicate ID properties

I have two arrays of objects that I need to merge, but I want to exclude any objects with duplicate IDs (I only want to keep the first object with each ID).

One array is stored locally, and the other is retrieved from an API.

const localUsers = [
    {
        "id": 1,
        "first_name": "Adam",
        "last_name": "Bent",
        "avatar": "some img url"
    },
    {
        "id": 2,
        "first_name": "New Name",
        "last_name": "New Last Name",
        "avatar": "some new img url"
    }

];

const apiUsers = [
    {
        "id": 2,
        "first_name": "Eve",
        "last_name": "Holt",
        "avatar": "some img url"
    },
    {
        "id": 3,
        "first_name": "Charles",
        "last_name": "Morris",
        "avatar": "some img url"
    }
];

The expected output should be skipping the object in apiUsers with the id: 2, as it already exists in the localUsers array. This exclusion should apply to all matching IDs.

const mergedUsers = [
    {
        "id": 1,
        "first_name": "Adam",
        "last_name": "Bent",
        "avatar": "some img url"
    },
    {
        "id": 2,
        "first_name": "New Name",
        "last_name": "New Last Name",
        "avatar": "some new img url"
    },
    {
        "id": 3,
        "first_name": "Charles",
        "last_name": "Morris",
        "avatar": "some img url"
    }

];

Answer №1

To create a new array called mergedUsers, combine localUsers and apiUsers, excluding any duplicates from localUsers:

const localUsers = [
    {
        "id": 1,
        "first_name": "Adam",
        "last_name": "Bent",
        "avatar": "some img url"
    },
    {
        "id": 2,
        "first_name": "New Name",
        "last_name": "New Last Name",
        "avatar": "some new img url"
    }

];

const apiUsers = [
    {
        "id": 2,
        "first_name": "Eve",
        "last_name": "Holt",
        "avatar": "some img url"
    },
    {
        "id": 3,
        "first_name": "Charles",
        "last_name": "Morris",
        "avatar": "some img url"
    }
];

const mergedUsers = localUsers.concat(apiUsers.filter(a => !localUsers.find(b => b.id === a.id)));
console.log(mergedUsers);

Answer №2

To organize the arrays in a specific order, you can utilize a Map and reduce the arrays accordingly.

const
    localUsers = [{ id: 1, first_name: "Adam", last_name: "Bent", avatar: "some img url" }, { id: 2, first_name: "New Name", last_name: "New Last Name", avatar: "some new img url" }],
    apiUsers = [{ id: 2, first_name: "Eve", last_name: "Holt", avatar: "some img url" }, { id: 3, first_name: "Charles", last_name: "Morris", avatar: "some img url" }],
    result = Array.from(
        [localUsers, apiUsers]
            .reduce(
                (m, a) => a.reduce((n, o) => n.set(o.id, n.get(o.id) || o), m),
                new Map
            )
            .values()
    );

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

Answer №3

To start, eliminate all instances from the apiUsers array that are also found in the localUsers array. Then, combine the filtered array with the localUsers array. The order of the elements in the final array is not specified in the question, but it can be easily accomplished.

const result = apiUsers.filter(user => !localUsers.some(localUser => user.id === localUser.id));
const mergedArray = [...localUsers, ...result];

Answer №4

If you want to merge two objects with duplicates, you can simply use the following code:

Array.prototype.push.apply(primaryUsers, secondaryUsers);

After merging the two objects, you can then remove any duplicate entries.

For more information, check out this helpful resource: Merging 2 arrays of objects

Answer №5

  1. Remove users from the apiUserArray that already exist in the localUserArray.
  2. Combine both arrays.

    let uniqueApiUsers = apiUsers
                            .filter(apiUser => !localUsers
                                              .some(localUser => localUser.id === apiUser.id))
    
    let combinedArray = localUsers.concat(uniqueApiUsers)
    

Answer №6

If you want to create your own custom comparison function, it's actually quite simple:


    for(var x=0; x<myList.length; ++x) {
        var match = 0;
        for(var y=x+1; y<theirList.length; ++y) {
             if(myList[x]['key'] === theirList[y]['key']){
                  theirList.splice(y--, 1);
             }
        }
    }
    console.log(myList.concat(theirList));

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

Extracting real-time weather information using API and sharing it on Twitter

I'm currently facing challenges with adapting my twitter weather bot due to the recent changes in Apixu endpoints (now weatherstack). I am currently stuck trying to resolve the issue with the code below. Issue resolved ...

The API call within the app's service.js is not communicating with the page's controller

When my app accesses an API, it retrieves an array of 'card' objects and showcases each one on the user interface. The HTML file for card search is: card-search.html <div class="main-view container"> <h1>Card Search</h1> ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

order in which child objects are drawn

Encountering the following issue: I am attempting to create rings around Saturn, but they appear to be rendered in an incorrect order: https://i.sstatic.net/rVg3H.jpg The problem lies in how each planet is constructed. Each planet is a child of a differ ...

Implementing a dynamic dropdown list with pre-selected values within a while loop

Is there a way to have the selected value in a dropdown list reflect a value given by a JavaScript function that updates a GET parameter in the URL when an option is chosen? <?php while ($row = mysql_fetch_array($res)) { echo '<option value=&ap ...

Executing a PHP function within an AJAX method

I'm currently working with the code below and trying to figure out how to call a function from a file called functions.php and pass $var1 as a parameter. Can anyone lend some guidance on how I can achieve this? $(document).ready(function() { ...

Adapt the stylesheet for mobile devices using CSS

I am struggling with updating file paths in CSS depending on whether the end user is accessing my site from a PC or mobile device. Below is my CSS code, where I attempted to redirect users if they are on a handheld device: <link rel="stylesheet" type=" ...

Ensuring that the form button is reset automatically upon using the browser's "Back" button

Even after exploring numerous similar questions and trying out various suggested solutions, I still can't seem to get anything to work. The issue I'm facing involves a form on a webpage. To combat the problem of impatient individuals clicking &a ...

Tips for creating text that adjusts to different screen sizes within a div

I am trying to ensure that the height on the left side matches the height on the right, so it's important that it looks good on various devices like tablets, PCs, etc. However, when I resize my browser window, the video on the right side shrinks while ...

Material UI button text not receiving props

Within my application, I have a situation where I utilize data attributes on buttons to gather specific contextual information in the modal that is triggered by clicking the button. This functionality depends on accessing the data attributes through e.targ ...

Utilize a Fancybox hyperlink for every image within the specified div container

I'm looking for a solution to automatically add a fancybox link to every image within the div #artikel. Essentially, I want to convert each <img src="image.png"></img> to <a href="image.png" class="fancybox" rel="artikel"><img ...

Is it true that when you return from a callback in JavaScript, it gives back

Here's the code I'm working with: function retrieveSocialCount(type, filePath, executeCallback){ var request = new XMLHttpRequest(); request.onload = function(){ if(request.status === 200 && request.readyState === 4){ ...

Interacting with data and functions in Vue using addEventListener

I'm encountering difficulties connecting my data or methods using this code: created() { document.addEventListener( 'touchstart', function( e ) { this.myData = e.changedTouches[ 0 ].screenY } } I presume the issue lies in the scope ...

Experiencing an excessive amount of re-renders in React due to useState

In this scenario, the user is expected to press the correct letter on the keyboard (which is the first letter of the bird's name) in order to delete the first bird's name from the birds array. This process repeats until the array is empty. Howeve ...

Tips for converting mobile numbers into clickable links using JavaScript

I am working on an HTML page where data is being dynamically loaded, including some mobile numbers. I'm looking for a way to wrap all these mobile numbers in anchor tags using JavaScript. For example: <a href="tel:+91 9999999999">+91 9999999999 ...

How can I dynamically swap one div with another within the same div using Javascript?

I have a piece of code that I am working with, and I need it to replace every div element whenever a specific div is clicked. function updateContent(target, replacementID) { document.getElementById(target).innerHTML = document.getElementById(replaceme ...

Completely enlarge this inline-block CSS div scan-line

I am looking to create a unique scan line effect that gradually reveals text from left to right, mimicking the appearance of a cathode-ray burning text into a screen's phosphors. The concept involves sliding across black rows with transparent tips. Y ...

Can multiple `npm install` commands run at the same time?

Is it possible to have concurrent runs of npm install, or will they conflict on shared resources and create potential race conditions? Analyzing the code might not provide a clear answer, but for those working on developing npm, this is likely an implicit ...

Numerous buttons activating a single modal component

I have an array called videos, which contains objects of the type Video (defined below). My goal is to create a functionality where clicking on a specific video button opens a modal containing information about that particular video. interface VideosInfo ...

Dynamically uploading an HTML file using AJAX

My webpage has a feature that dynamically creates HTML with drop down elements. Additionally, there is a "create File" button on the page. The goal is for this button to trigger an AJAX POST request and upload the dynamic page created with drag and drops a ...