Creating a concatenated multidimensional array can be achieved by combining multiple arrays of varying lengths into a single multidimensional array

Is there a way to transform array a into array b?

Alternatively, how can I create a matrix-style multidimensional array using the values from array a below?

SPECIFICATIONS: 1. The length of array a is variable. 2. Each element in array a has a variable length as well.

const a = [
  ['red', 'blue'],
  ['small', 'medium', 'large'],
]

const b = [
  ['red', 'small'],
  ['red', 'medium'],
  ['red', 'large'],
  ['blue', 'small'],
  ['blue', 'medium'],
  ['blue', 'large'],
]

Example 2:

const a = [
  ['quadcore'],
  ['4GB', '8GB'],
  ['black', 'grey'],
]

const b = [
  ['quadcore', '4GB', 'black'],
  ['quadcore', '4GB', 'grey'],
  ['quadcore', '8GB', 'black'],
  ['quadcore', '8GB', 'grey'],
]

Answer №1

To extract elements from multiple arrays and create combinations, you must iterate through each array and push the elements one by one. Below is a code snippet demonstrating this:

function extractElements(arr)
{
  let n = arr.length;
  let result = [];
  let indices = new Array(n);
  
  for(let i = 0; i < n; i++)
        indices[i] = 0;

  while (true)
  {
      // Extract current combination
      let tmp = [];
      
      for(let i = 0; i < n; i++){
          tmp.push(arr[i][indices[i]]);   
      }
      
      result.push(tmp);

      let next = n - 1;
      
      while (next >= 0 && (indices[next] + 1 >= arr[next].length))
          next--;

      if (next < 0)
          break;

      indices[next]++;
      
      for(let i = next + 1; i < n; i++)
          indices[i] = 0;
  }

  return result;
}

const a = [
  ['quadcore'],
  ['4GB', '8GB'],
  ['black', 'grey'],
];

console.log(extractElements(a));

References: https://www.geeksforgeeks.org/combinations-from-n-arrays-picking-one-element-from-each-array/

Answer №2

You can easily tackle this issue by implementing a basic reduce() function.

const elements = [
  ["apple", "banana"],
  ["small", "medium", "large"],
];

const result = elements.reduce((accumulator, current) => {
  const storage = [];
  for (const item of accumulator) {
    for (const element of current) {
      if (Array.isArray(item)) {
        storage.push([...item, element]);
      } else {
        storage.push([item, element]);
      }
    }
  }
  return storage;
});

console.log(result);

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

Troubleshoot your Vue.js application using Visual Studio Code. Encounter an unidentified breakpoint error

I'm encountering a problem with debugging my Vue.js project using VS Code and Chrome. I followed the official guide on the website Guide, but it's not working for me. The error I keep running into is: unverified breakpoint What am I doing wrong? ...

Passing data from one component to another in Vue: A database perspective

I'm struggling to pass the id of a clicked button from MovieTable.vue to the WatchedForm.vue component. The WatchedForm.vue component is responsible for updating the data in the database based on the provided id, which corresponds to the Movie_id in t ...

When individuals discuss constructing a stack, or a full stack, in JavaScript, what exactly are they referring to and how does this concept connect with Node JS?

I recently started learning about node.js, but I'm struggling to understand its purpose. I have experience with JavaScript/jQuery and Angular, so I don't see how Node can benefit me. People keep talking about full stack JavaScript but I'm st ...

Is there a way retrieve all named HTML tags and store them in an array?

In need of assistance with parsing data from a page that is formatted as follows: <tag>dataIwant</tag> <tag>dataIwant</tag> <tag>dataIwant</tag> <othertag>moarData</othertag> <othertag>moarData</oth ...

What is the best way to switch from using the three.js JSONLoader to the ObjectLoader?

I successfully loaded multiple files using the code below for three.js JSONLoader: <!DOCTYPE html> <html> <head> <title>Rotating Sphere</title> <meta charset="utf-8"> <!-- https://cdnjs.com/libra ...

Eliminating duplicate uploads in JavaScript

Within my HTML code, there is a section where users can drag and drop files for upload. Inside this area, there is also a "browse for files" button that triggers a hidden file input if users prefer the traditional upload method. Everything functions correc ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

Issue with rendering in sandbox environment versus localhost

Here's a dilemma I'm facing - I have some HTML code on my localhost that looks like this: <div> <p>Go to: <a href="www.foobar.com">here</a></p> </div> On localhost, the output is "Go to: here" with 'he ...

An error occurred while processing the JSReport request

I am encountering an issue while trying to utilize the jsreport API for rendering a report template. The error I am facing is as follows: { body: "{"body":"\"{\\\"template\\\":{\\\"shortid\\& ...

Issue with express-validator returning undefined value on forms set to enctype='multipart/form-data'

Currently, I am developing a login authentication application using basic node.js+express. While extracting values (such as name, email, etc) from the registration page, I utilize express-validator for validation. However, I encounter an issue where all va ...

When employing UI-Router, custom directives may not function properly within nested views

I was developing an angular application using phonegap, ionic, and angular. I had created a custom directive that registered an event listener for the element to activate iScroll upon loading. Initially, the directive worked perfectly when all the views we ...

Tips on avoiding a page reload following a form submission using JQuery

Currently developing a website for my app development project, I've encountered an unusual issue. Utilizing some JQuery to transfer form data to a php page called 'process.php' and then add it to my database. The strange part is that the pa ...

Moving the layout container towards the left: a quick guide

I am currently attempting to display the legend contents in a horizontal alignment within the layout container. The issue is that while the layout containing the legend aligns horizontally as desired, it extends beyond the screen border. I do not want the ...

Error encountered when trying to generate a collection from JSON using Backbone framework

jQuery(function() { var Hotel = Backbone.Model.extend({ defaults: { idHotel:"", hotelName:"Grand Marina", hotelAddress:"Lakeview Drive", hotelStars:"4", hotelRoomsCount:"180", ...

Retrieve Vuejs template by either module or ID

In my .Vue file, I have defined a template along with its subcomponents with the intention of allowing customers to override this template without needing to modify any javascript code. If there exists an element with id="search-result", then that element ...

The variable that was posted is not being successfully transferred within the query

There seems to be an issue with retrieving data from the ajax call in ajaxcall.php and assigning it to $place = $_POST['place']; in listplace.php. Despite this problem, the code runs smoothly otherwise. I've tried numerous times to get the ...

Verify that the user visits the URL in next.js

I need to ensure that a function only runs the first time a user visits a page, but not on subsequent visits. For example: When a user first opens the HOME page, a specific condition must be met. When they then visit the /about page, the condition for th ...

Filtering data from Arduino using web serial communication

My setup consists of an Arduino kit connected to a webserial API that sends data to an HTML div identified by the id 'target'. Currently, all the data is being logged into one stream despite having multiple dials and switches on the Arduino. Th ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

Mapping an array with array objects - a guide to connecting and iterating through

I am working with two arrays: ['x', 'y', 'z'] And array 2: [{ x: 5, y: 10, z: 15, w: 20 }] Is there a way to merge these two arrays to get the following output: [{x: 5, y: 10: z: 15}] I only want the items present in the fi ...