Merge the individual elements from multiple arrays to create a final unique array using JavaScript

I am working with two data structures:

const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];

I have a specific outcome in mind:

finalArr = [["name1", "123", "prop2",156, 154, "position report], ["name2", "43", "prop22",173, 124, "position report"],["name3", "22", "prop3", 136, 154, "position report"]]

To achieve this, I attempted the following code but it did not fully merge the sub-array elements:

let newArr = [];
arr1.forEach((item) => {
arr2.forEach((element) => {
  newArr.push({ ...item, element });
   });
});

console.log(newArr);

Are there any solutions using only ES6 syntax?

Answer №1

If you want to combine two arrays in JavaScript, you can utilize the array.map method to transform the source array. Use the index i to access the corresponding element, and employ the spread operator to merge the arrays together:

const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];

let result = arr1.map((item, i) => [...item, ...arr2[i]]);
console.log(result);

Answer №2

To reorganize the information, you can create new arrays.

This method is effective even with multiple arrays.

const
    array1 = [["John Doe", "25", "red"],["Jane Smith", "32", "blue"], ["Alex Johnson", "45", "green"]],
    array2 = [[156, 154, "report A"],[173, 124, "report A"],[136, 154, "report A"]],
    result = [array1, array2]
        .reduce((r, a) => a.map((v, i) => [...(r[i] || []), ...v]), []);

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

Answer №3

Here's an example of how you can achieve this:

const firstArray = [["item1", "123", "attribute2"],["item2", "43", "attribute22"], ["item3", "22", "attribute3"]];
const secondArray = [[156, 154, "status update"],[173, 124, "status update"],[136, 154, "status update"]];

let resultArray = [];
if (firstArray.length === secondArray.length) {
  for(let index=0; index<firstArray.length; index++){
     resultArray.push([...firstArray[index], ...secondArray[index]]);
  }
}

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

There seems to be a glitch in the angularjs application

This is my code for the Services.js file: angular.module('RateRequestApp.services', []). factory('rateRequestAPIservice', function($http) { var rateRequestApi = {}; rateRequestApi.getData = function () { retur ...

Transferring information among PHP web pages using a list generated on-the-fly

I am working with a PHP code that dynamically generates a list within a form using data from a database: echo '<form name="List" action="checkList.php" method="post">'; while($rows=mysqli_fetch_array($sql)) { echo "<input type='pas ...

What is causing React Js to fail loading css when switching from anchor tag to link tag?

I am learning React and experimenting with creating a basic static website using HTML templates in version ^18.2.0 of React JS. Everything seems to be functioning correctly, however, I have encountered an issue with page refresh. Specifically, when I repla ...

What could be causing my web application to not properly identify angular.js?

As a newcomer to angular, I have been struggling to incorporate it into my web application (VS) as I keep encountering issues with recognizing angular. Despite trying various methods, the result remains the same - angular is not being recognized. I dow ...

Having trouble getting past the "Starting metro bundler" step when using the 'expo start' or 'npm start' command?

Currently, I am using React Native Expo to develop a mobile application. The process I followed includes the following steps: expo init myapp cd myapp expo start Initially, everything was running smoothly after executing these three commands. However, as ...

Sorry, but you can only use one 'in' filter in your query

this.ref.collection("users", ref => ref.where("uid1","in", [reciverId, senderId]) .where("uid2","in", [reciverId, senderId])) throws an error stating: "Invalid query. Multiple 'in' filters cannot be used." ...

Utilizing Laravel to Showcase Google Maps with Custom Markers Generated from MySQL Data

As I work on developing a web application that involves integrating Google Maps and multiple markers, I encountered an issue this morning. Initially, I successfully implemented the map with markers from a single database table. However, my goal now is to ...

Trigger an Event Handler only after ensuring the completion of the previous event handling

When attaching an event handler to a callback, it is important to consider the timing of the actions. For example: $("someSelector").on('click',callBackHandler); function callBackHandler(){ //Some code $.ajax({ //Ajax call with succe ...

JavaScript - Unable to unselect a button without triggering a page refresh

I have a series of buttons in a row that I can select individually. However, I only want to be able to choose one button at a time. Every time I deselect the previously selected button, it causes the page to reload when all I really want is for all the but ...

Incorporate CSS styling from a separate .css file into a material component

Just starting out with material UI. I have a css file that looks like this: .bgItem { font-size: 14px; } My component setup is as follows: <MenuItem key={status.Id} value={status.Value} classes={css.bgItem}> {status.Description} </Men ...

Utilizing IISNode and/or nodemon for efficient node.js development on Windows platform

For my node.js application running on Windows, I currently utilize IISNode both locally during development and on production hosting. Would incorporating nodemon (or a comparable module that monitors file changes and restarts node.exe when necessary) pro ...

Creating a unique Nest.js custom decorator to extract parameters directly from the request object

I am working with a custom decorator called Param, where I have a console.log that runs once. How can I modify it to return a fresh value of id on each request similar to what is done in nestjs? @Get('/:id') async findUser ( @Param() id: stri ...

Understanding Express.js API Function Parameters

The API documentation for Express mentions that the format for a function is "app.use([path,] function [, function...])". However, in the app.js file generated by the Express generator, there is a line of code like this: "app.use('/', routes);", ...

Server-side Data Fetching with Nuxt.js

Is there a method to exclusively retrieve data from an API on the server-side in NuxtJS due to me needing to include my API_TOKEN in the request headers? Sample Code: <template> <div> <h1>Data obtained using asyncData</h1> ...

Enhance Your Text Areas with Vue.js Filtering

Currently, I am working with a textarea that has v-model: <textarea v-model="text"></textarea> I am wondering how to filter this textarea in Vue. My goal is to prevent the inclusion of these HTML quotes: &amp;amp;#039;id&amp;amp;#039 ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Stopping Angular.js $http requests within a bind() event

As stated in this GitHub issue Is it expected to work like this? el.bind('keyup', function() { var canceler = $q.defer(); $http.post('/api', data, {timeout: canceler.promise}).success(success); canceler.resolve(); } ...

What are some techniques for concealing error messages?

Can you assist in resolving this issue? There is a form which displays the inscription "You break my heart" immediately after loading, but I need it to only appear after the user attempts to enter text in the form. <div ng-app=""> <f ...

The process of displaying custom number buttons on the correct input field in react.js

I am facing a challenge in implementing this feature. I have created custom number buttons from 0-9 that users can click on instead of using the keyboard. The issue arises when there are multiple dynamically generated input fields based on JSON Data. For e ...

Tips for retrieving values from numerous checkboxes sharing the same class using jQuery

Currently, I am struggling with getting the values of all checkboxes that are checked using jquery. My goal is to store these values in an array, but I am encountering difficulties. Can anyone provide me with guidance on how to achieve this? Below is what ...