Merge two arrays of objects together and eliminate duplicates based on a specific attribute

I am currently working with two arrays of objects. One array retrieves data from an API to display in the application, while the other array fetches data from localStorage, which includes modifications made to the original data stored in the first array. My goal is to combine these two arrays, but I need to ensure that there are no duplicate objects to prevent redundant rendering.

Here's an example of the desired outcome:

data1 = [
  {customer: {
    purchased: false,
    id: 1
  }}, 
  {customer: {
      purchased: false,
      id: 2
  }}
]

data2 = [
  {customer: {
    purchased: true,
    id: 1
  }}
]

data3 = data1.concat(data2)

result: 
data3 = [
  {customer: {
    purchased: true,
    id: 1
  }}, 
  {customer: {
    purchased: false,
    id: 2
  }}
]

I have been struggling to find an effective way to compare the two arrays. Despite brainstorming various approaches, I have been unsuccessful in my attempts.

Answer №1

Is something similar to this?

const data1 = 
      [ { customer: { purchased: false, id: 1 } } 
      , { customer: { purchased: false, id: 2 } } 
      ] 
const data2 = 
      [ { customer: { purchased: true, id: 1 } } 
      ] 


const data3 = data1.map(item=>
  {
  let newItem = data2.find(x=>x.customer.id === item.customer.id )
  return newItem? newItem : item
  })

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

But be cautious, this is an array of objects within objects so it's recommended to use

const data3 = data1.map(item=>
  {
  let newItem = data2.find(x=>x.customer.id === item.customer.id )
  return newItem? JSON.parse(JSON.stringify(newItem)) : JSON.parse(JSON.stringify(item))
  })

if you want a completely new array

Answer №2

To ensure that your customer objects are unique, you can achieve this by utilizing the id field for mapping. In this method, entries from the second object will have priority, giving precedence to local storage over API results:

let mergeCustomerData = (arr1, arr2) => {
  
  // Convert both arrays into maps, with the `item.customer.id` property as the key
  [ arr1, arr2 ] = [ arr1, arr2 ].map(arr => new Map(arr.map(v => [ v.customer.id, v ])));
  
  // Combine these maps into one (consider order of `arr1` and `arr2` for preference)
  let merged = new Map([ ...arr1, ...arr2 ]);
  
  // Return the merged values, converted back into an array
  return [ ...merged ].map(([ id, v ]) => v);
  
};

let customerArray1 = [
  { customer: { purchased: false, id: 1 } }, 
  { customer: { purchased: false, id: 2 } }
];

let customerArray2 = [
  { customer: { purchased: true, id: 1 } }
];

console.log(mergeCustomerData(customerArray1, customerArray2));

Answer №3

Retrieve the identifiers from the second array. The output will be the combination of the second array along with all elements from the first array that have an identifier not present in the stored identifiers.

data1 = [
  {customer: { purchased: false, id: 1 }}, 
  {customer: { purchased: false, id: 2 }}
];

data2 = [
  {customer: { purchased: true, id: 1 }},
  {customer: { purchased: true, id: 5 }}
];

function combineData( data1, data2) {
    let output = data2;
  let ids = [];
  data2.forEach(element => ids.push(element.customer.id));
 
  data1.forEach(element => {
    id = element.customer.id;
    if ( ids.indexOf(id) == -1 )
        output.push(element);
  });
  
  return output;
}
 
console.log( combineData( data1, data2));

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

What are the steps to start a ExpressJS server for webpages that are not index.html?

I am exploring how to browse/run/view web pages other than just the index.html file in my public folder, which contains multiple HTML files. I am using ExpressJS and NodeJS for this purpose, but every time I start my server, I can only access the index.htm ...

Mat-SideNav in Angular Material is not toggled by default

<mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button> <mat-icon (click)="sidenav.toggle()">menu</mat-icon> </button> <h1>{{applicationN ...

Using Three.js to extract Vertex Colors based on the z-coordinate of Vectors

Here is a sample: http://jsfiddle.net/c3shonu7/1/ The code demonstrates the creation of a BufferGeometry object by cloning an IcosahedronBufferGeometry's vertices. The goal is to apply a color gradient to the subdivided icosahedron, with lighter shad ...

Using jQuery, retrieve JSON data from a different domain URL, even if the JSON data is not well-structured

Currently, I am utilizing jQuery's ajax function to access a URL from a different domain which returns JSON data. During my testing phase, I've encountered an issue where the presence of multiple '&quot' strings within the JSON valu ...

I am experiencing an issue where the submit button in my HTML form is unresponsive to clicks

Welcome to my HTML world! <form action="petDetails.php" id="animalInput"> <ul> <li> <label for="dogName">Enter Dog's Name:</label><input id="dogName" type="text" name="dogName" /> </l ...

Facing a dilemma: Javascript not updating HTML image source

I am facing an issue while attempting to modify the source of my HTML image element. Despite using document.getElementId('image') in my code, I am unable to make it work as intended. Surprisingly, there are no errors displayed. Interestingly, whe ...

Customize your payment with a PayPal button tailored to your desired price

I've been tasked with creating a dynamic PayPal button that can receive different values based on user choices. The website has so many options that creating separate buttons for each choice doesn't seem feasible. I've tried researching solu ...

retrieving request headers using XMLHttpRequest

Is there a way for me to access my requestHeaders within the onload function? Any guidance on how to achieve this would be greatly appreciated. Many thanks! ...

In Vue.js, I only want to retrieve and display the parent's ID or name once for each of its child components

<td v-if="currentId != loop.id" class="text-center"> <div :set="currentId = loop.id">{{ loop.id }}</div> </td> <td v-else></td> Looking to achieve a specific layout like this This invo ...

Having difficulty changing the visibility of a div element

I am currently working on a project that involves jQuery and ASP.Net. My main goal is to create a button that can hide/show a div using jQuery. Below is the code that I have implemented: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLI ...

What is the best way to enable a link upon clicking while simultaneously disabling the others using JavaScript?

When I click on a link, I want to handle just that one element. However, when I click on another link, the active class is not being removed from the previous ones. Can anyone offer assistance with this issue? Here's my code: let parentT = document.qu ...

RadAjaxNamespace is not found within the codebase

While testing the application on my development machine, I encountered an error message in the browser debug console stating "RadAjaxNamespace is not defined". Interestingly, this error does not appear when accessing the production server. Upon comparing t ...

How to dynamically add an input textbox after a selection change in YUI JavaScript?

Is there a way to add an extra input textbox after an onchange event in a selectbox using the YUI library? I need to utilize YUI and the form is generated with PEAR Quickforms lib. This is what I have so far: $form->addElement('select', &ap ...

Using Strapi to showcase images in a React frontend

I am currently in the process of developing a website utilizing Strapi as a Content Management System (CMS) and Next.js with React for the Frontend. The website features an image slider that includes an image, a headline, and a description. While I have su ...

Assigning a price to a list of pizza options within a dropdown menu

//The goal is to assign a numerical price to each pizza in the array. We must maintain the structure of the array within the select form. Next, we need to display it in another PHP file, how do we retrieve the values? <fieldset> ...

absence of data in ajax response (or HTTP status code 206 Partial Content)

Feeling frustrated because I've wasted two hours trying to solve a simple task that I've done numerous times before. I'm not even sure where to start looking now. Struggling to retrieve static content using ajax from local servers (Apache a ...

Two airplanes in such close proximity to each other

Currently dealing with an issue involving two planes positioned very closely together. One of the planes is causing glitches or disappearing from certain angles. Check out the following code snippet: var renderer, scene, camera, controls, mesh; init(); ...

Changing Array into a JSON Document

I have been utilizing JSONKit to transform the data stored in my .json file into an NSMutableArray. I am now looking for a way to revert this array back to JSON data and save it back to the file. Are there alternative Kits or methods that could achieve t ...

Show a picture without specifying its file location

Looking for Suggestions on a New Title I am interested in using a script as the source attribute for an image, like this : <img src="img.js"/> Note: I am open to using any programming language, whether it be javascript or php. Here is what my fol ...

Automatically refreshing controller functionality in CodeIgniter

Greetings everyone, I'm looking for a way to automatically refresh a controller function every 5 seconds. Currently, I am using header('Refresh: 10.2'); within the controller function like this: public function delete() { heade ...