Using Javascript to merge the components of a multidimensional array

I'm currently working on a project that involves combining elements from a multidimensional array to create different combinations.

For example, if I have the following array:

var array = [
      ['a'],
      ['1', '2', '3', '4'],
      ['A']
];

The desired output would be:

["a1A", "a2A", "a3A", "a4A"]

To achieve this result, I have implemented the following code:

var finalArray = [];
var f1 = 0;

for (var i = 0; i < array.length - 1; i ++) {
    f1 = 0;
    for (var j = 0; j < array[i].length; j ++) {
        for (var k = 0; k < array[i + 1].length; k ++) {
            if (finalArray[f1])
                finalArray[f1] += array[i + 1][k];
            else 
                finalArray[f1] = array[i][j] + array[i + 1][k];

            f1 ++;
        }
    }
}

console.log(finalArray);

The issue arises when additional elements are added to the first or last member of the array, as the code does not produce the expected output.

For instance, consider the following array:

var array = [
      ['a', 'b'],
      ['1', '2', '3', '4'],
      ['A']
];

Instead of getting:

["a1A", "a2A", "a3A", "a4A", "b1A", "b2A", "b3A", "b4A"]

The code currently returns:

["a1A", "a2A", "a3A", "a4A", "b1", "b2", "b3", "b4"]

If anyone has suggestions on how to improve this code to handle additional elements correctly, please let me know. Your help is greatly appreciated.

Answer №1

One way to handle variable lengths of parts and their lengths is by using a combination of iterative and recursive techniques.

function mix(array) {
    function m(part, index) {
        array[index].forEach(function (a) {
            var p = part.concat(a);
            if (p.length === array.length) {
                res.push(p.join(''));
                return;
            }
            m(p, index + 1);
        });
    }

    var res = [];

    m([], 0);
    return res;
}

var output = mix([['a', 'b', 'c'], ['1', '2', '3', '4'], ['A', 'B']]);

document.write('<pre>' + JSON.stringify(output, 0, 4) + '</pre>');

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

Generate unique identifiers to rotate images dynamically on the webpage

My goal is to rotate every image on a page, and while this works with a single image, it only rotates the first one since each ID needs to be unique. I need to find a way to dynamically increment the IDs as they are encountered on the page. Below is what I ...

Steps for resetting the counter to 0 following an Ajax Refresh or Submission to the database

I have been working on a code that successfully sends multiple data to a MySQL Database using JQuery Ajax. Everything works smoothly, but I encountered an issue when trying to refresh the page with ajax and add a new record; it populates the number of time ...

Searching for attributes in a JSON document

Currently, I am dealing with a results API that provides me with a JSON file. My goal is to search for a specific property within this file. To achieve this, I first push the JSON data into an empty array and then iterate over it to retrieve the first obje ...

modify a column in a database table when a different field is chosen

I am working on a basic table with 4 columns, two of which are dropdown menus with the classes "ddm1" and "ddm2". Here is what I am trying to achieve: Users should not be able to select from "ddm2" until they have selected an option from "ddm1". When ...

"Utilizing Node JS to find the index of an object within an array

I have been encountering an issue with finding the index of an object in an array. Despite my efforts, I always receive -1 as the index unless I resort to a workaround. Both methods seem identical and produce the same console output. Is this perhaps a bug ...

Implementing a filter on retrieved data from an API in a React application

I'm retrieving information from this Api After fetching the data, I need to check if the gender is Male in order to display a Male Icon. How can I perform this check on the Api data and return some HTML data like an img tag or something to show the i ...

Identify the significance within an array and employ the filter function to conceal the selected elements

I'm in the process of filtering a list of results. To do this, I have set up a ul list to display the results and checkboxes for selecting filter options. Each item in the ul list has associated data attributes. When a checkbox with value="4711" is c ...

Adjust Vue FilePond dimensions

I am currently working with a Vue Filepond and trying to ensure that it fills the height of its container. My Vue Filepond setup also involves Vuetify. Whenever I attempt to set values in the CSS, they are constantly overridden by 76px. Although fill-hei ...

stop tabs from being visible during window reload

I am currently working on a page that features 4 jQuery UI tabs. The first tab simply displays a greeting message saying "HELLO". The 2nd, 3rd, and 4th tabs contain HTML and PHP scripts that are functioning correctly. However, when I execute the PHP script ...

Ensure that confirmation is only prompted in ASP.NET when necessary

I am faced with a scenario where I need to handle the value of Session["actionMode"] in conjunction with a button click event. Here is what I currently have implemented in my code: protected void Button1_Click(object sender, EventArgs e) { if ((int)S ...

Searching for a MongoDB document using its unique identifier

Currently, I am working with Node.js and MongoDB where my database is hosted on MongoHQ (now compose.io). I have come to understand that document IDs are converted to hex strings, but I am struggling to retrieve a document using its ID. In my dataset, the ...

Issue with Passing 'key' Prop to React Component in a Mapped Iteration

https://i.sstatic.net/qeFKT.pngI'm struggling with adding a key prop to a React component in a mapped array within a Next.js project. The issue lies in a Slider component and an array of Image components being mapped. Even though I have provided a uni ...

Can someone assist me in determining the UV mapping process from Ricoh Theta S Dual Fish Eye to a Three.js r71 SphereGeometry?

Currently, I am attempting to replicate the three.js panorama dualfisheye example using Three.js version r71. It is crucial for me to adhere to r71 because I plan to integrate this code into the Autodesk Forge viewer, which relies on Three.js r71. I have ...

"Error encountered: Module not found - Issue resolving module" while using signrequest-client in Angular

I've been attempting to integrate the signRequest API into my angular application. To do so, I first installed the signrequest-client using the following command: npm install signrequest-client --save Following this installation, I included the Ja ...

Looking to create a GitHub example in Fiddle but running into issues with getting the result?

I've been working on an example on Fiddle, but it's not functioning as expected. I want to implement i18next so that the text changes when the user switches languages. After searching for a solution, I came across this GitHub repository: https:// ...

What could be causing input to be blocked in certain situations while using my Angular directive with compile function?

Recently, I created a directive that adds a class based on a certain condition. You can find the code snippet at the end of this question. The directive functions as expected in a simple use case where it's applied to a required field: <input typ ...

The Vue EventBus does not support passing object attributes

Looking for assistance with integrating two Vue single page components. The 'Searchbar' component features a dialog box where users input data. This data is required in the 'ResultList' component for further processing. To achieve this ...

Navigable Vuetify Tabs with routing capabilities

Within my Vue application, I have a page that contains various tabs. My goal is to display different tabs based on the routes being accessed. To achieve this functionality, I followed an answer provided in this link. Overall, it's working well! I ca ...

Navigating with Link in React Router DOM v5 to successfully pass and catch data

In the process of developing a basic chat application, I encountered an issue with passing the username via the Link component. Below is the relevant code snippet: <Link to={{ pathname: `/${room}`, state: { the: user } }}> Enter room </Link> ...

Triggering the open() function within an Ajax request

Upon experimenting with the method open(), I discovered that it requires a URL file as an argument. For instance, I have two functions named generateGeometricShapes() and colorShapes(). I am contemplating whether I should create separate files for each fu ...