Combine three arrays by a predetermined index value to generate a consolidated array

I have three arrays that share the same first index, and I am looking to combine them into one array based on the first index element.

Input:

[[1, 'A'], [2, 'B'], [3, 'C']];
[[1, 'D'], [2, 'E'], [3, 'F']];
[[1, 'G'], [2, 'H'], [3, 'I']];

Expected output

[ 
  [ 1, 'A', 'D', 'G' ], 
  [ 2, 'B', 'E', 'H' ], 
  [ 3, 'C', 'F', 'I' ] 
]

Here is my code for achieving this:

function mergeArrays(arrays) {
  const mergedMap = new Map();

  for (const array of arrays) {
    for (const item of array) {
      const key = item[0];
      if (!mergedMap.has(key)) {
        mergedMap.set(key, [key]);
      }
      mergedMap.get(key).push(...item.slice(1));
    }
  }

  const mergedArray = Array.from(mergedMap.values());

  return mergedArray;
}

const array1 = [[1, 'A'], [2, 'B'], [3, 'C']];
const array2 = [[1, 'D'], [2, 'E'], [3, 'F']];
const array3 = [[1, 'G'], [2, 'H'], [3, 'I']];

const mergedResult = mergeArrays([array1, array2, array3]);
console.log(mergedResult);

Do you have any suggestions for improving this solution?

Please note: in my actual scenario, the first index is a Date object rather than a number for simplicity.

Answer №1

Using lodash library

const _ = require('lodash');
function combineArrays(arrays) {
  return _.chain(arrays)
    .flatten()
    .groupBy((item) => item[0])
    .mapValues(L1=>_.uniq(_.flatten(L1)))
    .values()
    .value();
}

const array1 = [[1, 'Apple'], [2, 'Banana'], [3, 'Cherry']];
const array2 = [[1, 'Date'], [2, 'Fig'], [3, 'Grape']];
const array3 = [[1, 'Kiwi'], [2, 'Lemon'], [3, 'Mango']];

const combinedResult = combineArrays([array1, array2, array3]);
console.log(combinedResult);

//desired output
[ 
  [ 1, 'Apple', 'Date', 'Kiwi' ], 
  [ 2, 'Banana', 'Fig', 'Lemon' ], 
  [ 3, 'Cherry', 'Grape', 'Mango' ] 
]

Answer №2

That particular type of function is often referred to as zip, but with three arrays, let's name it zip3:

function zip3(f, a, b, c) {
  var ret = [];
  var max = Math.min(a.length, b.length, c.length);
  for (var i = 0; i < max; i++) ret.push(f(a[i], b[i], c[i]));
  return ret;
}

This function applies f to elements at the same index, like this: f(a[0], b[0], c[0]). Since each element is also an array, we use destructuring to access the data.

Here are some examples:

zip3( ([index, a], [, b], [, c]) => [index, a, b, c]
    , [[1,'A'],[2,'B'],[3,'C']]
    , [[1,'D'],[2,'E'],[3,'F']]
    , [[1,'G'],[2,'H'],[3,'I']]);

//=> [[1,'A','D','G']
//=> ,[2,'B','E','H']
//=> ,[3,'C','F','I']]

zip3( ([index, a], [, b], [, c]) => [c, b, a, index-1]
    , [[1,'A'],[2,'B'],[3,'C']]
    , [[1,'D'],[2,'E'],[3,'F']]
    , [[1,'G'],[2,'H'],[3,'I']]);

//=> [['G','D','A',0]
//=> ,['H','E','B',1]
//=> ,['I','F','C',2]]

zip3( ([index, a], [,b], [,c]) => ({x: a, y: b, z: c, index})
    , [[1,'A'],[2,'B'],[3,'C']]
    , [[1,'D'],[2,'E'],[3,'F']]
    , [[1,'G'],[2,'H'],[3,'I']]);

//=> [{x: 'A', y: 'D', z: 'G', index: 1}
//=> ,{x: 'B', y: 'E', z: 'H', index: 2}
//=> ,{x: 'C', y: 'F', z: 'I', index: 3}]

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 a MODULE NOT FOUND error when using express.js

const express = require("express"); const app = express(); const path = require("path"); app.use(express.static(staticPath)); let staticPath=path.join(__dirname, ".."); There seems to be an error in these lines of ...

Raycasting in three.js - mouse pointer and highlighting not precisely aligned with intersected mesh

My current setup involves using a raycaster to highlight a row of cubes arranged in a grid format. The highlighting works fine, but I'm encountering issues with the cursor turning into a pointer precisely over the cubes in the row. Moreover, the highl ...

What is the reason for utilizing two separate loop variables when implementing merge sort on an array?

As I was delving into the world of merge sort for integer arrays, I stumbled upon an interesting observation. It seems that while transferring the sorted array elements back to the original array, it requires the use of two distinct loop variables to ensur ...

What prevents me from calling a function while it is being defined in the prototype?

I am experimenting with inheritance through an example. I want to access all properties of objects abc and pqr, so I decided to use Object.create. However, when I try to get the value of r by calling the getr() function, it doesn't seem to work as exp ...

Apply a border to the input field when the user enters or leaves the field, only if the value is

I am managing a few input fields and storing their information in an object. My goal is to click on an input field to focus on it, and if the field is empty or has a length greater than or equal to 0, I want it to display a red border. If I type somethin ...

Display a pop-up notification to a user one time

Looking to enhance the user experience on my website, I want to display a pop-up alert only during the first visit and not on subsequent visits. As someone with limited HTML and scripting skills, can you guide me on how I can achieve this using cookies or ...

Attempting to modify Namecheap's custom DNS field through Python Selenium

I am facing an issue while attempting to modify DNS settings for domains in Namecheap using Python Selenium Below is the HTML code: <select class="dashed-select add-margin ng-untouched ng-valid select2-offscreen ng-dirty ng-valid-parse" ng-change="nam ...

Constant updating of webpage elements without the need for a complete page reload

Is there a way to refresh a top bar similar to Facebook, where the number of messages updates without refreshing the entire page? I know how to do this if the top bar is separate from the main page using meta tags, set timeout, or a refresh tag. However, ...

What is the best way to silence console.log outputs during testing?

There is a utility function that needs to be tested: var util = function(data) { ..... console.log('msg'); .... return true } Here's my test.js file: describe('Testing the util function', function () { it(&ap ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Step-by-step guide on concealing elements and subsequently displaying them upon clicking the containing DIV

It's a bit tricky to explain without visuals, so I suggest checking out the JSFiddle link provided. Essentially, when a specific div is clicked, it should expand to reveal some inputs and buttons. However, the issue I'm facing is that upon loadin ...

Angular-Formly: Defining the Label and Description for the Primary Selection Element

I'm currently using the Angular Formly library (http://angular-formly.com/) and I've hit a roadblock while trying to add a description under the label of a Select dropdown. app.controller('CalcCtrl', function CalcCtrl(formlyVersion, fo ...

Is it possible to utilize AJAX requests in order to create a marker on google maps that updates in real-time?

My goal is to develop an app that generates a real-time updating google map, and I have been advised that AJAX requests can help achieve this. Nevertheless, after studying the documentation, I am uncertain about how to apply this method to solve my issue ...

The .load() function is compatible with Internet Explorer and Dreamweaver for preview, however, it does not work

Having trouble getting this code to work in Chrome, and it's crucial for my Android development. Can anyone spot the error? I simply need to load 'page1.html' into '#container1'. It should be a simple task, and it was working fine ...

Using Lightmaps with Three.js

Is it true that lightmaps function independently of other textures? It seems like I need to establish a second set of UVs. I've exported my JSON object with a second set of UVs and included the following code snippet: geometry.faceVertexUvs[0] = ge ...

Tips for including data labels in a scatter plot using d3.js

I am currently studying d3.js for data visualization and I have chosen to work with the titanic dataset My objective is to incorporate passenger names into my visualization so that when a cursor hovers over a point, the person's name is displayed. H ...

Tips for displaying only the items that are currently visible in an AngularJS Dropdown

I am currently working with an AngularJs object that looks like this: $scope.data = {'options': [{ "id": 1, "text": "Option 1", "isHidden": 0 }, { "id": 2, "text": "Option 2", "isHidden": 1 }, { "id": 3, "text": "Option 3", "isHidden": 0 }]}; U ...

Adjust the package.json file for deployment

I've encountered a problem while attempting to deploy my nodejs application on Heroku. Despite following the documentation and modifying files in the root directory, I have not been successful. Below is the structure of my package.json file: { ...

Removing a child node in a JSON data structure

I am dealing with the following JSON data. My goal is to remove only the children nodes from the array while keeping the rest of the content intact. { "model_type_name": "portfolio", "hier_model_type_name": "portfolio", "object_type": "product", "gen_new_ ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...