Combining two arrays of objects using unique keys in Angular 8

There are two Arrays of Objects, Arr1 and Arr2. The goal is to merge these two arrays based on their 'id' values. If Arr1 does not contain any object with the same id as in Arr2, then that particular object node should be pushed into Arr1. How can this be achieved?

Arr1 =
[
  {
    'id': 101,
    'name': "ABC"
  },
  {
    'id': 202,
    'name': "DEF"
  }
];

Arr2 =
[
  {
    'id': 303,
    'name': "PQR"
  },
  {
    'id': 404,
    'name': "XYZ"
  },
  {
    'id': 202,
    'name': "DEF"
  }
];

Arr1 =
[
  {
    'id': 101,
    'name': "ABC"
  },
  {
    'id': 202,
    'name': "DEF"
  },
  {
    'id': 303,
    'name': "PQR"
  },
  {
    'id': 404,
    'name': "XYZ"
  }
];

Answer №1

Iterate through the elements in Arr2 using the forEach method. Inside the callback function, utilize the findIndex method to determine if the current element being iterated over is present in Arr1. The findIndex method will return the index of the element if found in the array, or -1 if not found. If the result of findIndex is -1, then add that item from the second array to Arr1.

let Arr1 = [{
    'id': 101,
    'name': "ABC"
  },
  {
    'id': 202,
    'name': "DEF"
  }
];

const Arr2 = [{
    'id': 303,
    'name': "PQR"
  },
  {
    'id': 404,
    'name': "XYZ"
  },
  {
    'id': 202,
    'name': "DEF"
  }
];

Arr2.forEach((item) => {
  const isPresentInArry1 = Arr1.findIndex(elem => elem.id === item.id);
  if (isPresentInArry1 === -1) {
    Arr1.push(item)
  }
});

console.log(Arr1)

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

How can Action type be inferred from mapping object to ensure type safety when using useReducer dispatch?

Welcome Message Usually, my approach to defining a reducer involves ensuring type safety with the dispatch method as shown below: const setItems = (state: State, payload: Partial<State>) => ({ ...state, ...payload }); // Assigns an action type t ...

Retrieving information from a local JSON file in Vue.js using the jQuery $.getJSON() method

Currently, I am in the process of developing a demo application using Vuejs which involves extracting map data from a local .json file. The extracted data is then used to obtain specific information like latitude and longitude values that are necessary for ...

Repeating audio playback in HTML5 with a pause option

I need to set up a loop with a 10-minute delay. Once the loop starts and finishes, there should be another 10-minute delay before it automatically restarts again. $audio_code = '<div style="display: none;">' . '<audio id="war_sound ...

How to send a JSON object using Node.js Express 4.0

I'm currently working on parsing the JSON object sent in the request and displaying the data being transmitted. Below is my post request: $.ajax({ url: url, type: 'POST', contentType: 'application/json' ...

Ways to insert a color into an HTML text box based on a condition

Hey everyone, I need some help with changing the color of a textbox in cshtml. Here is the code snippet I am working with: $("#BUTTON").click(function (event) { var urlPA = URL; var crty = $("#Courtesy").val(); var fname = $("#Familyname").val ...

What is the best way to prevent the chaining of promises and catches in JavaScript?

I am currently developing an API using node and express to create users. However, I find myself struggling with error handling due to the asynchronous nature of MongoDB functions, which makes me feel like I'm trapped in a "promise hell." I anticipate ...

Can a callback in an ES6 class constructor ensure that the promise is either resolved or rejected?

I'm currently puzzled by the concept of using a callback function that always returns an empty object and then passing a parameter to this callback. Visit this link for more information My assumption is that this approach ensures that the Promise wi ...

Why is Selectpicker failing to display JSON data with vue js?

After running $('.selectpicker').selectpicker('refresh'); in the console, I noticed that it is loading. Where exactly should I insert this code? This is my HTML code: <form action="" class="form-inline" onsubmit="return false;" me ...

Unique rewritten text: "Displaying a single Fancybox popup during

My website has a fancybox popup that appears when the page loads. I want the popup to only appear once, so if a user navigates away from the page and then comes back, the popup should not show again. I've heard that I can use a cookie plugin like ht ...

Autocomplete feature shows usernames while storing corresponding user IDs

I am looking to enhance the autocomplete functionality in my application while also ensuring that the selected user ID is stored in the database. Specifically, I want the autocomplete feature to display user names for selection purposes, but instead of re ...

angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index ...

Incorporate a CSS framework into the Angular vendor bundle

My current situation : The website is built with Angular 4 Started using Angular Starter Kit Utilizing Semantic UI as the CSS framework The challenge I'm facing : Integration of Semantic UI into webpack is not having any impact. Steps I've ...

What is the most effective way to receive notifications when an OAuth response has been received?

I have implemented Facebook and Google sign in using ionic with Firebase. My setup includes 2 services - FirebaseService.js, AppService.js, and a controller dashboard.js. I am trying to receive the OAuth response in the controller. What would be the most ...

I'm encountering an issue with the React state where it seems to be endlessly nesting

I am new to React and I seem to be encountering an issue where every time I trigger a click event, the state object continues to nest. The code snippet below is part of the App component. const [state, setstate] = useState('') useEffect(() =& ...

Ways to activate and deactivate the Delete button in a GridView using Jquery when the checkbox is left unchecked

I am struggling with getting my Delete button to disable and enable based on whether a checkbox is checked in a GridView using JQuery. The code I currently have is not working as expected. If anyone could provide assistance in a clear and easy-to-understa ...

Tips for executing jsfiddle code within Joomla 3.2

I'm having trouble executing this code on my Joomla website. I have Joomla 3.2 installed with the JCK Editor, but the HTML tags are not functioning correctly. Can someone please assist me in running the following code: $("#text10").keyup(functio ...

Using JQuery to incorporate carousel elements

I am currently developing an insertion form that adds a product to a [ products draft ]. This involves working with two tables: one named ( Drafts ) and the other named ( items ). Each item in the "items" table has a corresponding draft ID associated with ...

The SyntaxError message indicates that there was an unexpected non-whitespace character found after the JSON data when parsing it

I received an Error message: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data Here is the code snippet: <script> $(document).ready(function () { $('.edit1').on('change', function () { ...

Mastering the art of using wildcards in CSS can help you harness the power of recognizing attributes

I am facing a situation where I have an HTML table with numerous cells, some of which are assigned classes like hov1, hov2, ..., hov42, ..., all the way up to hov920. This is a compact table where the darker green cells (hov1) change when hovered over whi ...

Implementing Voting Functionality with Ajax Submission

Can anyone help me with getting ajax functionality to work properly for my Acts_As_Votable buttons? Here's the current code I have: post_controller.rb def favorite @post = Post.find(params[:id]) @post.upvote_from current_user respond_to do |f ...