What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows:

  const input_array= [
    ["red", "green"],
    ["small", "medium"],
    ["x", "y", "z"]
    //... can have any number of rows added dynamically
  ];

How can I transform this array into the following format?

const finallist = [
    ["red", "small", "x"],
    ["red", "small", "y"],
    ["red", "small", "z"],
      
    ["red", "medium", "x"],
    ["red", "medium", "y"],
    ["red", "medium", "z"],

    ["green", "small", "x"],
    ["green", "small", "y"],
    ["green", "small", "z"],
      
    ["green", "medium", "x"],
    ["green", "medium", "y"],
    ["green", "medium", "z"],
  ]

Keep in mind that the input_array can vary in size.

I'm looking for advice on how to achieve this transformation. Thanks!

Answer №1

Take a look at this interesting code snippet:

const input_array = [
    ["red", "green"],
    ["small", "big"],
    ["x", "y", "z"]
    //... can be dynamically added with more rows
];
const mmc = input_array.reduce((e, r) => e * r.length, 1);
const finallist = input_array.map((x,i)=>({index:i,arr:x})).reduce((e, r) => {
    for (var u = 0; u < mmc; u++) e[u] && (!r.arr.some(r => e[u].includes(r)) || e[u].length <= r.index) ? e[u].push(r.arr[u % r.arr.length]) : e.push([r.arr[u % r.arr.length]]);
    return e.sort(), e
}, []);

Warning! Be careful as running this code on large matrix scales may cause issues in your browser.

Answer №2

This code snippet demonstrates how to create combinations from an input array:

const input_array = [
    ["black", "blue"],
    ["large", "medium"],
    ["a", "b", "c"]
]
const getCombinations = array =>
  array.reduce((v, b) =>
    v.reduce((r, g) => [...r, ...b.map(w => [].concat(g, w))], [])
  )
console.log(getCombinations(input_array))

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

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

Exploring the reactivity of Vue on object graphs that include cyclic references

First and foremost, let me provide some context: I am currently in the process of developing a minesweeper application using VueJS. The grid is structured as an object tree, where each Box object contains a 'neighbors' property that stores Box o ...

What is the best way to calculate the variance between the most recent and previous data points in an array in the span of an hour using JavaScript

Here is an array of objects I am working with: 0: {time: '2021-12-02T23:53:54.062Z', value: 558316} 1: {time: '2021-12-03T00:53:53.959Z', value: 558452} 2: {time: '2021-12-03T01:53:53.934Z', value: 558588} 3: {time: '2021 ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

Adding Vuetify to a Vue web component, then proceed to pass props to enhance its functionality

Currently working on developing a web component with Vue and using vuetify component library. The goal is to export it as a web component, but facing difficulties when trying to pass props to the exported component in the index.html file. Following the ste ...

When using Vue, it is important to ensure that dynamic slot names error templates are solely utilized for accurately mapping the state to

I am encountering an issue with Vuejs(2.6.11) Dynamic Slot Names: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed. Why is this error occurri ...

Nuxt.js i18n Failing to Display Pages in Default Locale Without Redirecting

I'm currently developing a Nuxt.js project with internationalization (i18n) using the @nuxtjs/i18n module. My goal is to serve pages in French as the default locale without redirecting to /fr/... when no specific locale is provided in the URL (e.g., a ...

Troubleshooting: Magento checkout page keeps scrolling to the top

We are experiencing an issue where, during the one page checkout process, the next step is not automatically scrolling to the top of the page when it loads. After a user fills out all their billing information and clicks continue, the next step appears ha ...

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Navigate back to the previous page without reloading

Initially, I must clarify that the title of my query may not be entirely representative of what I wish to convey. The situation at hand is as follows: I have developed a jQuery table designed for exhibiting video records. Embedded within this table is a hy ...

Tips for launching a colorbox within a specific div container

I am looking to implement a color box that opens without a popup and only shows/hides inside a specific div. Is it possible to target a div to open the colorbox content? <a href='#myGallery' class='group'>click here</a> &l ...

AngularJS is not immediately responsive to changes in $window.document.visibilityState

I am currently working with AngularJs version 1.4 and I need to be able to detect when a user is not on the tab of my app and when they return. To achieve this, I attempted using $watch in the following way: $rootScope.$watch(angular.bind($window, functio ...

Please note: With React 18, the use of ReactDOM.render is no longer supported. Instead, we recommend using create

I encountered an issue while attempting to link my React application with a MongoDB database. Here is the code snippet where the problem occurred: //index.js ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> &l ...

Adding a regional iteration of a library that was unable to be loaded

Recently, I have been experimenting with PhantomJS to capture screenshots of a webpage every five minutes. While the process runs smoothly most of the time, I encountered an issue where the AngularJS library fails to load intermittently. This results in th ...

Sending information back to the server without causing a postback, all while remaining unseen

I have a straightforward JavaScript function on my ASP.NET page that writes data to a hidden field. However, in order to retrieve this data the form needs to be submitted back to the server. The issue is that submitting the form causes the page to reload ...

Can Googlebot detect changes made to an HTML <title> tag using JavaScript?

Within my website, I have a search engine that operates using ajax technology. My goal is to assign a unique <title> for every search request made. This involves modifying the title each time I receive a response from the ajax feature. I am wonderin ...

Ways to continuously refresh the display in AngularJS

There are 2 div elements below, and I need to display only one of them depending on whether the doStuff() function is triggered in the controller when a specific anchor element is clicked. <div ng-controller='myController'> <div ng- ...

The request to login at the specified API endpoint on localhost:3000 was not successful, resulting in a

As I continue to develop my programming skills, I have been working on configuring a database connected with nodejs in the same folder. However, when trying to make an ajax request to the database, I encountered an error indicating that the database may be ...

The process of displaying custom number buttons on the correct input field in react.js

I am facing a challenge in implementing this feature. I have created custom number buttons from 0-9 that users can click on instead of using the keyboard. The issue arises when there are multiple dynamically generated input fields based on JSON Data. For e ...