What is the best way to combine two arrays and generate a new array that includes only unique values, similar to a Union

Here are two arrays that I have:

X = [
   {
      "id": "123a",
      "month": 5,
      "markCount": 75
   },
   {
      "id": "123b",
      "month": 6,
      "markCount": 85
   }
]
Y = [
   {
      "id": "123a",
      "month": 4,
      "markCount": 45
   },
   {
      "id": "123b",
      "month": 3,
      "markCount": 65
   },
   {
      "id": "123c",
      "month"": 2,
      "markCount": 55
   }
]

The Goal I want to combine array 'X' with array 'Y' to form a new array Z. Array Z should contain all the unique objects from 'Y' and update any common id values with information from array 'X'. I attempted using the set function, but it did not return only the unique items: Z = [...new Set([...X, ...Y])]

Z = [
   {
      "id": "123a",
      "month": 4,
      "markCount": 75
   },
   {
      "id": "123b",
      "month": 3,
      "markCount": 85
   },
   {
      "id": "123c",
      "month": 2,
      "markCount": 55
   }
]

Answer №1

If you attempt to reach them and then sort through elements that exist within the array already,

C = A.concat(B).filter((el, i, arr) => arr.findIndex(cEl => cEl.id === el.id) === i);

it will eliminate any duplicates present.

Answer №2

Take a look at the solution provided in this answer which utilizes ES6 Map.

However, in your scenario, you should replace 'member' with 'id'

The code snippet might resemble something like this:

A = [{
    "id": "111a",
    "week": 2,
    "percentComplete": 50
  },
  {
    "id": "111b",
    "week": 2,
    "percentComplete": 60
  }
]
B = [{
    "id": "111a",
    "week": 1,
    "percentComplete": 20
  },
  {
    "id": "111b",
    "week": 1,
    "percentComplete": 30
  },
  {
    "id": "111c",
    "week": 1,
    "percentComplete": 40
  }
]

const merged = [...A.concat(B).reduce((m, o) =>
  m.set(o.id, Object.assign(m.get(o.id) || {}, o)), new Map()).values()];

console.log(merged)

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

Encountering an error stating "Argument of type 'X' is not assignable to parameter of type 'X' in the NextApiResponse within NextJS."

Here is the code snippet I am working with: type Data = { id: string; name: string; description: string; price: number; }; const FetchMeals = async (req: NextApiRequest, res: NextApiResponse<Data>) => { const response = await fetch( ...

Utilizing Vue.js and Webpack to Handle Requests for Multiple Incorrect Resource Links

After utilizing Vue.js single file components to construct a website and appreciating the modular approach, I've encountered an issue. The browser appears to be requesting multiple versions of resources instead of just one URL for each. HeaderBar.vue ...

Executing a Node.js script using an absolute path

In the process of developing a basic app using Node.js and Express, I've encountered an issue. The script is located at path/to/script/server.js. When I run this script with node server.js while in the correct directory, everything functions correctly ...

Revising text for real-time editing

Most of us are familiar with the functionality on StackOverFlow that allows you to preview your text before posting a question. I'm interested in implementing a similar feature on my website and am looking for some guidance on how to get started. I ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

After a certain time has passed, an event will occur once a div element has been assigned

Is there a way to show div2 only after div1 has been given the '.selected' class for a set duration, and then hide it again when div1 loses the '.selected' class? What would be the most efficient approach to achieve this? ...

During the installation of a package, npm encountered a require stack error with the code MODULE_NOT_FOUND

Whenever I attempt to install something using the npm install command, it throws an error saying "require stack" and "code MODULE_NOT_FOUND" C:\Users\dell>npm audit fix node:internal/modules/cjs/loader:1075 const err = new Error(message); ...

Send back Complex data type to display using AJAX

My Objective I am dealing with a complex type generated by EF from a stored procedure. This type returns a list of GetAvailableRooms_Results. I want the user to choose two dates and then get a list of available rooms (complex type) returned by the stored ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

Is there a need to remove whitespace for additional characters?

Is there a function available that can trim specified characters or strings? For example: var x = '@@@hello world@@'; console.log(x.trim('@')); // outputs 'hello world' var y = 'hellohellohelloworld'; console.log(y ...

Guide on disabling a hyperlink in a table column under specific conditions using Angular2

I am working with a table that has 4 columns: Name, id, Dept, City. The row data and column data are provided as an array from a typescript file and I am iterating through *ngFor to display the content. Below is a snippet of my code: <tbody> < ...

What is the best way to retrieve the height and width of a device's display in Angular 2 using Typescript

I came across this code snippet. Do you think it's valid? import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; @Component({...}) export MyApp { constructor(platform: Platform) { platform.ready().then ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

Unable to retrieve API data on local server port 5000. Utilizing a database sourced from a CSV file. Unexpected undefined promise response

I have been struggling for the past few days with a persistent issue. Seeking assistance. Currently working on a project involving a CSV database and creating my own API. It is a small React App Fullstack MERN setup. The specific challenge I am facing is ...

HTML - Retain placeholder text while user inputs

My input is structured like this: <input value="My text" placeholder="Placeholder"> Typing in the input causes the placeholder text to disappear, which is expected. However, I am looking to keep the placeholder text visible as a background behind ...

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

Troubleshooting the issue with integrating a user-defined Cordova plugin in Ionic 2 using TypeScript

I have developed a custom Cordova plugin and I am trying to integrate it with an Ionic 2 project that is using TypeScript and Angular 2. While I have successfully added the plugin to the Ionic 2 project, I am facing issues when trying to call methods defin ...

Adding a class to the current li element without affecting its siblings in Angular 2

I am dealing with a structure that looks like this: <div> <ul> <li> <ul> <li>Option 1</li> <li>Option 2</li> <li>Option 3</l ...