Combining two multidimensional arrays in JavaScript without altering the original arrays

Having trouble merging two complex arrays? Let's simplify it for you:

var array1 = [['email1', object1],['email2', object2],['email3', object3],['email4',object4]]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]

All you need to do is merge them by email, eliminating duplicates in the process:

var mergedarray = 
[['email1', object1, [['a1', 'b1']]],['email2', object2],['email3', object3, ['a3', 'b3']],['email4',object4,[['a4','b4'],['a4a','b4a']]]]

No need to overthink those multi-dimensions! Need any help with this?

Answer №1

   const emailHash = new Map();

   for(const [userEmail, ...otherData] of [...firstArray, ...secondArray]) {
     if(emailHash.has(userEmail)) {
       emailHash.get(userEmail).push(...otherData);
     } else {
        emailHash.set(userEmail, [userEmail, ...otherData]);
    }
  }

  const finalResult = [...emailHash.values()];

Answer №2

Implement a Map using the elements in array2 to improve search speed. Then utilize Array.prototype.map on the first array or vice versa.

var array1 = [['email1', 'object1'], ['email2', 'object2'], ['email3', 'object3'], ['email4', 'object4']]
var array2 = [['email1', [['a1', 'b1']]], ['email3', [['a3', 'b3']]], ['email4', [['a4', 'b4'], ['a4a', 'b4a']]]]

let map2 = new Map(array2);

let out = array1.map(([key, val]) => [key, val, map2.get(key) || []]);
console.log(out)

Answer №3

To iterate over the second array and validate if the first element is present in any of the arrays within the first array, you can then append the second element if the condition is met:

const firstArray = [['item1', 'data1'],['item2', 'data2'],['item3', 'data3'],['item4','data4']]
const secondArray = [['item1',[['param1','value1']]],['item3',[['param3','value3']]], ['item4',[['param4','value4'],['param4a','value4a']]]]

secondArray.forEach((sArr, idx) => {
  firstArray.map((fArr, fIdx) => {
    if (fArr[0] == sArr[0]) {
      firstArray[fIdx].push(secondArray[idx][1])
    }
  })
})

console.log(firstArray)

Answer №4

Having struggled to implement the given advice (likely due to my limited skill level), I resorted to transforming arrays into objects in order to assign key-value pairs. As a result, the new data structure looked like this:

var array1 = [{email:'email1', obj:object1, data:[]},{email:'email2', obj:object2, data:[]},{email:'email3', obj:object3, data:[]},{email:'email4',obj:object4, data:[]}];
var array2 = [{email:'email1',data:[{'a1','b1'}]},{email:'email3',data:[{'a3','b3'}]}, {email:'email4',data:[{'a4','b4'}]},{email:'email4',data:[{'a4a','b4a'}]}];

Subsequently, I utilized a loop to transfer object data from one array to another:

 for (var x in array1) {
    var res = array1[x].email;

    for (var z in array2) {
      var cod = array2[z].email;
      var q = 0;
      if (res == cod) {
        array1[x].data.push(array2[z].data[0]);
        q++;
      }

    }
  }

The end outcome is as follows:

var array1 = [{email:'email1',obj:object1,data:[{'a1','b1'}]},{email:'email2',obj:object2,data:[]},{email:'email3',data:[{'a3','b3'}]},{email:'email4',obj:object4,data:[{'a4','b4'},{'a4a','b4a'}]}];

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

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

Guide to utilizing Terser in conjunction with webpack

I am currently using Webpack 6.10.2 in combination with Vue 3.9.3. I encountered an issue with Uglify.js when running npm run build due to its inability to handle ES6 code. To work around this problem, I followed the recommendation of removing Uglify fro ...

JavaScript event listener 'click' not functioning properly

I'm facing an issue with a click event in a script that is associated with a specific div id. When I move the mouse within the div area and click (the cursor remains unchanged), the event listener does not activate. How can I make the div area clickab ...

Tips for shutting a window

Need help with closing a window upon button click - tried close() The window opens successfully, but closing it seems to be an issue I've set the isVisible property to false as needed, but still unable to close it <template> <q-dialog ...

Ensuring multiple checkboxes are selected is essential; failure to check at least one will result in an error message being

How can I ensure that the visitor chooses at least one option before submitting the form? Below is a snippet of my code: <div class="col-md-6" id="ajax_succs"> <div class="check_parent"> <input type="checkbox" name="sub_sub_cat_select[]" c ...

Greetings Universe in angular.js

Having trouble creating a Hello World page in angular.js. When I try to display {{helloMessage}}, it shows up instead of Hello World. I'm not sure where the issue lies. Within the folder are two files: angular.min.js and HelloWorld.html. In HelloWorl ...

Error encountered: "Unexpected token export" when using jQuery 3.2.1 with the latest Autonumeric Plugin

Having some trouble with the autoNumeric jQuery plugin for formatting USD input. I keep getting an 'Uncaught SyntaxError: Unexpected token export' error on line 5450 when using the latest version of Chrome on Linux. I made sure to call it after ...

What is the best method for retrieving the chosen value from a <select> element?

Can you help me figure out why I am receiving an array of empty strings in my JavaScript code even though I have HTML select elements with values selected? <select id="col_1" name="col_1" class="columnMapping"> <opt ...

Using Ajax to set the file target dynamically

Let me start by saying that I prefer not to use JQuery for any suggestions. I'm not a fan of how JQuery has become the de facto standard within JavaScript. Now, onto my issue: I want to pass a variable to a function that will then use that variabl ...

Give a jQuery Mobile flipswitch a new look

Currently, I am using jQuery Mobile and recently attempted to refresh a flipswitch. However, upon executing the code $("#flipEnabled").slider("refresh");, I encountered an error in the console: Uncaught Error: cannot call methods on slider prior to initial ...

Is there a way to continuously make changes to my MEAN stack code without needing to constantly restart `npm start`?

When running my MMEAN stack app (Mongoose, MongoDB, Express, AngularJS, and Node.js) using npm start, I find that every time I make a code change, I have to stop and start npm start again in order for the changes to appear on my web application. The consta ...

Puppeteer throwing an error when querying selectors cannot be done (TypeError: selector.startsWith is not a supported function)

I recently installed Puppeteer and ran into an issue when trying to query a selector. I keep receiving a TypeError: selector.startsWith is not a function error. I attempted to resolve the problem by tweaking the core code and adding toString(), but unfort ...

How can I update the source of an HTML video element seamlessly without causing any glitches?

I'm attempting to create a video call interface that plays videos generated based on user responses. I want the ability to seamlessly switch between the currently displayed video and the next generated video without the HTML collapsing and rebuilding ...

Retrieve values from an array of objects using their corresponding keys

I have an array populated with various objects containing different key-value pairs. I need to extract specific values from the array and determine if a certain value is present or not. function groupByName (contract) { const { age } = contract; const g ...

What is the best way to navigate through a JavaScript array?

After making an ajax call, I received the following output: "total":"3", "data":[{ "id":"4242", "title":"Yeah Lets Go!", "created":"1274700584", "created_formated":"2010-07-24 13:19:24", "path":"http:&bsol ...

Exploring the world of C-style arrays through Boost Hana

BOOST_HANA_DEFINE_STRUCT is an amazing macro for adding introspection to structure declarations. For example, if we have a structure like this: struct Employee { std::string name; std::string department; int employee_id; }; We can enhance it with i ...

Using popsicle with Node.js to handle asynchronous operations and promises

Looking for a way to optimize a function that currently makes a single API call, returning a Promise. How can we modify this code to make multiple API calls for different timestamps? The goal is to store the unaggregated data in an object with the timestam ...

Building an array of objects using a foreach loop

i am struggling to create an array of objects from two input groups, each group consists of 3 inputs with data-side attributes set to left or right every input has a class named "elm" and a data-pos attribute set to a, b, or c <input class="elm-left elm ...

`Creating a fluid MySQL table using JavaScript`

One of the challenges I'm facing involves working with a MySQL table that consists of 3 columns: MySQL db table +--+----+-------------+ |id|data|display_order| +--+----+-------------+ |0 |0 |2 | +--+----+-------------+ |1 |1 |1 ...

When utilizing the AWS JavaScript SDK, the request header is missing the HTTP_X_CSRF_TOKEN

In my Rails application, I have implemented a feature that allows users to post answers to questions via ajax. Everything was working fine until I decided to incorporate the aws-js-sdk script in order to enable image uploads within the answer input field. ...