What is the best way to merge two nested arrays of objects in JavaScript that share a common parent?

Hello everyone, I am facing an issue when trying to combine two nested parent arrays of objects. I want to merge only the children items that have the same group parent. Here is my scenario: I have two arrays

var arr1 = [{group: "a", items: ["a","b","c","d"]}, {group: "b", items:["k","l","m"]}];

var arr2 = [{group: "b", items: ["o","p","q","r"]}, {group: "c", items:["1","2","3","4"]}]

I need to merge these two arrays. If the second array has the same parent group, I want to simply add its items to the existing group, giving this expected result:

[
  {
     group: "a",
     items: ["a","b","c","d"]
  },
  {
     group: "b",
     items: ["k","l","m","o","p","q", "r"]
  },
  {
     group: "c",
     items: ["1","2","3","4"]

  },
]

In this case, arr1 and arr2 both have the same b group. Only the items will be combined in this scenario. I have tried searching everywhere for a solution but I'm still unable to figure it out. Your assistance would be greatly appreciated. Thank you in advance.

Answer №1

To merge two arrays together, you can utilize the Array.prototype.reduce method to group them based on a specific key such as group.

var array1 = [{group: "x", items: ["apple","banana","cherry","date"]}, {group: "y", items:["kiwi","lemon","mango"]}];
var array2 = [{group: "y", items: ["orange","pear","quince","raspberry"]}, {group: "z", items:["1","2","3","4"]}]

const groupedArrays = [...array1, ...array2].reduce((accumulator, current) => {
  accumulator[current.group] ? accumulator[current.group].items = [ ...accumulator[current.group].items, ...current.items ] : accumulator[current.group] = current;
  return accumulator;
}, {});

const result = Object.values(groupedArrays);
console.log(result);

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

error loading foursquare request

Hello everyone, I'm encountering a minor issue while attempting to access the foursquare api in order to gather information about a specific restaurant that I've entered into the search bar. Cross origin requests are only supported for protocol ...

Oops! Looks like we couldn't locate the request token in the session when attempting to access the Twitter API

Every time I attempt to connect to the Twitter API using Passport OAuth, an issue arises that redirects me to an error page displaying this message: Error: Failed to locate request token in session at SessionStore.get (/Users/youcefchergui/Work/ESP/socialb ...

Contrasting static and regular functions within a class

In this code snippet, I have defined a class named `className` with different types of functions. class className { constructor() { } static myStaticFunction() { console.log("myStaticFunction") } normalFunction() { console.log("normal ...

Organizing the website's files and extensions

Transitioning from programming desktop applications to websites can be overwhelming, especially when dealing with multiple languages and extensions like JavaScript, CSS, JSON, Bootstrap, Ajax, and PHP all at once. How do you effectively juggle these diff ...

Converting SOAP XML data into a PHP array

Whenever a service posts XML data to my URL, I use $data = file_get_contents('php://input');. It provides me with an XML string, but I'm struggling to convert it into a PHP array. Despite trying various solutions from Stack Overflow, I keep ...

Tips for adjusting the Material UI Tabs indicator's position with react-scroller

My customized MaterialUI Tabs component stacks all tab content for scrolling using react-scroller. The tabs work smoothly except the indicator does not update its position. The react scroller has props like onSetActive, onSetInactive, and activeClass whic ...

Store the Ajax response in localStorage and convert it into an object for easy retrieval and manipulation

I'm currently working on an Ajax request that retrieves JSON data from the server and then stores it in localStorage for use in my application. However, I feel like my current code may not be the most efficient way to accomplish this task, as I have t ...

Transferring complete objects between components in Angular 2

I'm facing an issue where I need to pass an object from one component to another. Within the first component, cinema.component.html, there is a function call that looks like this: <a title="Reserve" (click)="openReservationPage(repertoire)">Re ...

Issues with loading Angular 9 application on Internet Explorer 11

Having trouble with my app not loading in IE 11 after adding ngx-treeview. Encountering the error (SCRIPT1002: Syntax error), Script Error Error point in vendor.js Unsure how to resolve this issue. Works fine in chrome and firefox, but in IE11 all I se ...

The Angular.js resource REST request encountered a TypeError due to a function being undefined

My goal is to update data using a REST call. I have already made a GET request to populate the form, and upon clicking the update button, I intend to initiate a PUT call. However, instead of successfully executing the PUT call, I encounter a Type Error. B ...

Prevent users from navigating back after logging in on a Reactjs application

Is there a way to prevent users from using the browser's back button after redirecting them to another application in ReactJS? In my scenario, I have two applications running simultaneously. Upon successful login, I check the user type. If the conditi ...

JavaScript and the proper way to format the weekdays

Learning programming is new to me, so please bear with me. I am currently utilizing Informer, a reporting website that retrieves data from Datatel, a unidata database. My current task involves working on a computed column that only accepts Javascript and ...

How to arrange a group of arrays based on the size of each array within?

What is a method in PHP that can be used to organize an array of arrays based on the length of each array? Example: $parent[0] = array(0, 0, 0); $parent[2] = array("foo", "bar", "b", "a", "z"); $parent[1] = array(4, 2); $sorted = sort_by_length($parent) ...

click on separate buttons to reveal each iframe

I'm looking to optimize the loading of multiple iframes on my website by implementing a click function on buttons. For example, each button will correspond to a specific iframe - Button1 goes to iframe1, Button2 goes to iframe2, and so on. Currently ...

Steps to inject HTML content via id using a technology such as AngularJS' ng-include

My current project involves using AngularJS to compile a directive into the main page. This directive contains a series of buttons that dynamically change based on its internal state. I am interested in relocating these buttons to a menu-bar within the pag ...

javascript popup window with redirection functionality

Hello everyone, I need assistance with the code snippet below: echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Successfully Updated') </SCRIPT>"); I am trying to redirect the page to my edit.php after c ...

What is the method for activating the open feature in react-dropzone-component by utilizing refs?

Currently, I am utilizing the react drop-zone component to facilitate file uploads to the server. My objective is to trigger the drop-zone open function upon clicking a button. Here is what I have experimented with so far: To reference the drop zone, I ...

What is the best way to implement an onReady promise in a JavaScript application?

Exploring some Advanced topics in JS I am currently diving into and there is an interesting concept that's piqued my curiosity. I've been developing a VueJS application and now I'm looking to expose certain data and even methods from Vue ou ...

Command for Sniping with Discord.js

I am currently working on creating a snipe command using Discord.js in my bot. I have set up command handlers and everything seems to be working fine, including the on messageDelete event. However, I encounter an error when I delete a user message and try ...

How come the array list appears empty despite the fact that I included elements in it while making the request?

I'm facing an issue with my code where I am getting an empty array even though I have added elements to the array during the request. public class MainActivity extends AppCompatActivity { private List<Question> questionList; @Override protec ...