combine several arrays next to each other based on a specified key

I have a collection of three sets, each containing three elements:

Set1 = [[apple, 2, 4], 
      [banana, 5, 5],
      [cherry, 4, 1]]

Set2 = [[banana, 1, 7], 
      [cherry, 3, 8],
      [date, 5, 4]]

Set3 = [[apple, 5, 2], 
      [banana, 0, 9],
      [date, 3, 1]]

The desired output format is as follows:

[[apple, 2, 4, 0, 0, 5, 2],
 [banana, 5, 5, 1, 7, 0, 9],
 [cherry, 4, 1, 3, 8, 0, 0],
 [date, 0, 0, 5, 4, 3, 1]]

How can I transform the sets to achieve this output?

Answer №1

This will get the job done, although it may not be the most aesthetically pleasing ;)

const combineSiblings = (...elements) => {
   return elements.reduce((acc, current, index) => {
        current.flat();
        acc.push(...current);
        // Sort the array alphabetically by its first element
        return acc.sort((a ,b) => ((a[0] > b[0]) ? 1 : (a[0] < b[0]) ? -1 : 0));
    }, []);
}

let combined = combineSiblings(V1, V2, V3);

/* 
Manually concatenate the desired output since the placement of 0, 0 was not specified.
*/
let finalResult = [
    [
        ...combined[0].flat(),
        ...[0,0],
        ...combined[1].slice(1,3).flat()
    ],
    [
        ...combined[2].flat(),
        ...combined[3].slice(1,3).flat(),
        ...combined[4].slice(1,3).flat()
    ],
    [
        ...combined[5].flat(),
        ...combined[6].slice(1,3).flat(),
        ...[0,0]  
    ],
    [
        combined[7][0],
        ...[0,0],
        ...combined[7].slice(1,3).flat(),
        ...combined[8].slice(1,3).flat() 
    ]
];

Answer №2

To efficiently organize the values, you can store them in an object and then create an array with default empty values to assign the collected values.

var v1 = [['a', 2, 4], ['b', 5, 5], ['c', 4, 1]],
    v2 = [['b', 1, 7], ['c', 3, 8], ['d', 5, 4]],
    v3 = [['a', 5, 2], ['b', 0, 9], ['d', 3, 1]],
    parts = [v1, v2, v3],
    empty = Array(parts.length * 2 + 1).fill(0);
    temp = parts.reduce((r, a, i) => {
        a.forEach(([key, ...values]) => {
            r[key] = r[key] || { 0: key };
            for (let j = 0; j < values.length; j++) {
                r[key][i * values.length + j + 1] = values[j];
            }
        });
        return r;
    }, {}),
    result = Object.values(temp).map(v => Object.assign([], empty, v));

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

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

What is the module system that fabric composer utilizes for its logic JavaScript files?

I am currently in the process of creating a business-network-definition for Hyperledger using Fabric (based on generator-hyperledger-fabric). Everything has been running smoothly so far, but as we move onto our Proof of Concept (PoC), a few questions have ...

Tips for smoothly transitioning between tabs in IONIC by simply clicking on a link or url

Imagine having two tabs within my application: tab-one and tab-two. I am trying to navigate from the view of tab-one (one.html) to the view of tab-two (two.html). I have attempted using $state.go(), $location, and $window.location but none of them seem t ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Creating a single object from the union of two arrays with JavaScript

I'm looking for a way to merge two arrays into a single object named "data" but haven't discovered an efficient method yet. Here are the arrays: var X = [ 4, 5, 6 ]; var Y = [ d, e, f ]; Merge them into an object: var data = { Y: [ d, e, f ], ...

"Executing a query on Angular Firestore using the where clause fetches all documents from the

I am encountering a perplexing issue with my angular app that is connected to Firestore. Despite following the documentation closely, when I query for documents in a collection based on a specific condition, the array returned contains every single documen ...

Bringing the value from the codebehind to the jquery function on the client side

Here is the code snippet from my asp.net web application's code behind where I have integrated another web service: [WebMethod] public static string GetData(string name) { WEBSERVICE.Service1 Client = new Service1(); string Nam ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...

Negative vibes with for/in loop

My script is short and simple: hideElements = arguments.shift().split(','); for (iterator in hideElements) { console.log('--> hiding ' + hideElements[iterator]); lg_transitions({kind:"slide-up"}, {target: hideElements[iterat ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

Learn how to collapse a collapsible section in Jquery Mobile by clicking on a link. Check out the example on JSFiddle

Is there a way to make the data-role collapsible collapse when clicking a tab link? I've tried using an on-click function without success. Any ideas or alternative solutions? Thanks. Check out my JSFiddle, where you can see that the tabs change but t ...

Displaying only the validation messages that are accurate according to the Vuetify rules

<v-text-field label='New Password' class="required" v-model='password' type='password' :rules="passwordRules" required> </v-text-field> passwordRules: [ value => !!value || 'Pl ...

How can you deactivate all form elements in HTML except for the Submit button?

Is there a method available to automatically deactivate all form elements except the submit button as soon as the form loads? This would entail pre-loading data from the backend onto a JSP page while restricting user access for editing. Users will only be ...

Creating a dazzling pie chart using d3.js with JSON data

I'm having trouble generating a pie chart for my JSON data, as I keep encountering an error that I can't seem to figure out. Here is a snippet of my JSON file: {"data":[ {"ap": [ {"floorratio": [ {"floor":"Basement", "rat ...

What could be causing the data to not load from the database when the page is loaded?

My current setup involves a button that triggers a specific function upon loading. return ( <> <LikeButtonStyle onLoad={getUserData} onClick={addInfo}> <Image width="10px" height="auto" src="/ ...

How to specifically exclude a checkbox from the "select all" function in J

One way to select all checkboxes with HTML code: Select All <input type="checkbox" name='select_all' id='select_all' value='1'/> To achieve this with Javascript code: <script type="text/javascript> $(&apos ...

What is the process for executing mocha tests within a web browser?

Am I the only one who thinks that their documentation lacks proper instructions on running tests in the browser? Do I really need to create the HTML file they mention in the example? How can I ensure that it runs the specific test cases for my project? I ...

Issue arises when there are several inline <script> tags containing parameters which result in filtered JSON output

As a newcomer to JavaScript, I am faced with the challenge of creating a centralized glossary within a confined educational environment (LMS) that lacks a database or any other facilitating elements. My objective is to develop a script hosted on our applic ...

Retrieving multiple images from a directory and storing the image filenames in a JSON array

Currently, I am attempting to locate and retrieve the images stored within a specific folder using the following code. This code successfully retrieves the image names along with the total count of images. Subsequently, my goal is to save this information ...