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

Showing list data from script to template in vue - A step-by-step guide

My task involves displaying data from the main table in MySQL. I need to show the type of each major by comparing it with the id in the faculty table. I have successfully logged this information using console.log, but I'm unsure how to display it on t ...

Experience a unique custom layout using AppRouter in Next.js version 13, with the added

My goal is to encapsulate the _app.js file within a custom layout, similar to what I have done before. This way, I can include a Navbar at the top and wrap everything else within a container: //layout.js file import { Container } from 'react-bootstrap ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

Calculating the total of an array's values using JavaScript

Receiving information from an API and looking to aggregate the values it contains. Consider the following code snippet: function totalPesos(){ $http.get('/api/valueForTest') .then(function(data){ $scope.resumePesos = data.data.Re ...

Guide to downloading a file from a byte base64 in Vue.js

I am dealing with a byte base64 string let data = 'UEsDBBQABgAIAAAAIQBi7...' If I want to download the file from this byte base64 in vue js, what should I do? Any suggestions or solutions would be greatly appreciated :') ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Guide to incorporating a scroll-follow effect in multiple directions

I am facing a challenge with managing an array of divs that exceed the dimensions of their container. I have set overflow to hidden on the container and used JQuery Overscroll to achieve an iPhone-like scrolling effect on the map. The problem I'm try ...

Inconsistency in the invocation of PageMethod within AJAX script manager

My AJAX call to a method in the code-behind seems to be unreliable even though I have everything set up correctly. The JavaScript function utilizes PageMethods to invoke the method in the code-behind. While most of the time it works fine, occasionally it ...

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

Tips on ensuring data cleanliness in jQuery input fields

Before sending the ajax request, I want to sanitize the form fields for added security. Currently, my Javascript code looks like this: jQuery(document).ready(function($) { $('#login-form').submit(function(e) { e.preventDefault(); // pr ...

Attempting to retrieve nested data, only to be met with an undefined response

I've been attempting to retrieve specific information by iterating through the SearchResult object like so: for (let productKey in SearchResult) { if (SearchResult.hasOwnProperty(productKey)) { products.push({ name ...

Is there a problem with evalJSON() causing Simple AJAX JS to work on Safari locally but fail on the server and in Firefox?

I created a script that utilized Prototype's AJAX methods to fetch Twitter data in JSON format, process it, and display it within a div. The script was functioning perfectly during testing on Safari 4.0.3 on an OS 10.6.1 machine. However, when I uploa ...

What is the best way to pass a variable to the chrome.tab.create function?

Is there a way to pass a variable to the `chrome.tabs.create` function? I am currently working on setting up event listeners for my anchors, but I am faced with a challenge as I am creating them within a for loop: for (var i = 0; i < links.length; i++) ...

Transferring a JavaScript variable to PHP using AJAX does not display any output

My code is not working as expected. I am trying to pass a JavaScript variable with Ajax to PHP when the submit button is clicked, but the result does not display the var_data variable from JavaScript. Can someone help me identify what is wrong with my code ...

Steps to retrieve hexadecimal addresses sequentially

Can anyone recommend a module or script that can generate sequential 64-bit hex addresses like the following: 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000001 00000000000 ...

Achieve a seamless redirection to the 404 component in Angular without altering the browser URL, while ensuring that the browsing

Whenever my backend sends a 404 error (indicating that the URL is valid, but the requested resource is not found, such as http://localhost:4200/post/title-not-exist), I need Angular to automatically redirect to my NotFoundComponent without altering the URL ...

The functionality of remotely accessing autocomplete in Angucomplete Alt is currently not functioning properly

I'm currently experimenting with AngularJS autocomplete using Angucomplete Alt. I've copied the same code and running it on my local host, but unfortunately, no results are being displayed. When searching for the term 'ssss', an error ...

Discovering ways to determine if multiple strings are present within a single string using JavaScript

After writing this function, I noticed it only worked with a single string value. contains(input, words) { let input1 = input.split(' '); for (var i = 0; i < input1.length; i++) { if (input1[i] === words) { ...

Receiving an error of "Undefined" when attempting to retrieve an array that is nested within an object

I've been struggling with the same question for a while now. Despite my knowledge of dot and bracket notation, as well as attempts using empty keys, I'm still unable to make it work. The situation involves a JSON array of objects obtained from an ...