Creating a network of lists by combining multiple arrays

I'm currently working on generating a comprehensive list of all possible combinations of multiple arrays. While I have experience in Matlab and understand loops and basic coding principles, I'm unsure of the most efficient method to compile these arrays into a matrix of combinations. Initially, I created a matrix of all potential combinations, but realized it would be time-consuming to update each entry if I decided to add a new component to one of the arrays. I attempted to use the push command to address this, as shown below:

matrix=[array1, array2, array3]
var newMeat= 'pastrami'
matrix[1].push(bread[1] + '-' + newMeat + ....)

Although using the push command from a user interface (UI) seemed messy. For instance, I have a base array:

bread=['rye', 'white', 'wheat']

I aim to create combinations for each bread type with other arrays like

meat = ['roast beef', 'ham', 'turkey']
condiments = ['mayo', 'mustard','ketchup']

This would result in:

combinations = ['rye-roast beef-mayo', 'white-roast beef-mayo', 'wheat-roast beef-mayo', 
                 'rye-roast beef-mustard', 'white-roast beef-mustard', 'wheat-roast beef-mustard',
                 'rye-roast beef-ketchup', 'white-roast beef-ketchup', 'wheat-roast beef-ketchup']

and so forth. The columns would correspond to rye bread, white bread, and wheat bread respectively. Is there a specific term for this process I'm attempting? It should also accommodate additions to each array in the future. Appreciate any insights provided!

Answer №1

Utilizing three nested for loops to iterate through every possible combination:

var bread = ['rye', 'white', 'wheat'];
var meat = ['roast beef', 'ham', 'turkey'];
var condiments = ['mayo', 'mustard', 'ketchup'];

for (var b in bread) {
    for (var m in meat) {
        for (var c in condiments) {
            console.log (bread[b] + "-" + meat[m] + "-" + condiments[c]); // Display the combination as needed
        }
    }
}

Answer №2

To achieve the desired outcome, it is necessary to use one loop for each component.

3 levels of nested for loops

var bread=['rye', 'white', 'wheat'];
var meat = [ 'roast beef', 'ham', 'turkey'];
var condiments = [ 'mayo', 'mustard','ketchup'];

var result = [];
for(var i = 0; i < bread.length; i++) {
  result.push([]);
  for(var j = 0; j < bread.length; j++) {
    for(var k = 0; k < bread.length; k++) {
      result[i].push(bread[i] + '-' + meat[j] + '-' + condiments[k]);
    }
  }
}

console.log(result);

OR

3 levels of nested forEach loops

var bread=['rye', 'white', 'wheat'];
var meat = [ 'roast beef', 'ham', 'turkey'];
var condiments = [ 'mayo', 'mustard','ketchup'];

var result = [];
bread.forEach(function(b) {
  result.push([]);
  meat.forEach(function(m) {
    condiments.forEach(function(c) {
      result[result.length - 1].push(b + '-' + m + '-' + c);
    });
  })
});

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

Floating Action Button combined with a Material UI ListItem

I am working on creating a basic list with a listItem that includes a button. The code I currently have is as follows: import React from "react"; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider ...

Using Angular 2 for two-way binding with input masking

Encountering an issue with ng2 and inputmask. Here is the code snippet that's causing trouble: <div class="form-group col-sm-7"> <label class="control-label" for="sender-phone">Phone *</label> <input type="text" [(ngModel) ...

Tips for triggering several functions with a single onClick event in React?

I am currently working on a React Project where I have defined several functions to set conditions for rendering components on the page. However, I now need to be able to call all these functions again within the components when a button is clicked, in ord ...

Create an interactive HTML5 drag-and-drop interface that restricts the dropping of nested elements to only within form fields. This functionality is achieved

I have implemented Sortable.JS in a form builder to enable drag and drop functionality. My goal is to allow users to drag sections (which is mostly working) and questions within those sections, either within the same section or into other sections. The is ...

Is it possible for a single PHP query to manage multiple AJAX requests from various pages simultaneously?

My PHP page is called update_details.php?id=xyz. This page has a query that gets user details and updates their login time. Each user has a unique profile page named profile.php?id=xyz. So, the profile pages are different for each user such as profile.php ...

Reduce the amount of times append is used in JQuery

Whenever I click the button in Jquery, I aim to limit the number of appends that occur. function standardRoom() { var counter = 0; if ($('select#selectBoxStandard option').length > 1) { counter++; $('#selectBoxStandard&ap ...

Switching the image backdrop with an assortment of pictures

I am working with a structure that looks like this: <div class="container"> <ul> <li> <img> </li> </ul> </div> Currently, there is a background image set for the main container. My go ...

"Engaging with the touchscreen inhibits the triggering of click

Within this div, I have implemented touch-action:pan-y;. Surrounding this div is an anchor tag. If you click on the div, the link will successfully redirect. However, if you swipe on the div and then click, the link won't work on the first attempt bu ...

How can I access clipboard information within the ng-paste directive?

Currently, I am working with angularjs 1.3.2 and I'm seeking a way to retrieve the clipboard data during a paste event. Can anyone provide guidance on how to achieve this? This question is similar to the one found at: "Paste" event in Angul ...

I am having trouble getting JQuery tablesorter to work, what am I missing?

As a newcomer to jQuery, I am attempting to implement Tablesorter, but unfortunately, it does not seem to be functioning properly on my table (the styling remains unaffected by the tablesorter css, and the sorting functionality is non-existent). Below is ...

decide whether to use webpack bundling during development or not

Whenever I save a file, it takes around 30 seconds for the changes to reflect. I am currently using gulp watch and webpack for bundling around a hundred files. Is there any way to speed up the build process? ...

What is the best way to alter the header in Django when a user is authenticated?

In my project, I have two headers: header.html and headersuccess.html. When a user is logged in, I need to change the header from header.html to headersuccess.html. How can I implement that? Here is an excerpt from my views.py file where I render loginsuc ...

JSON data parsing error: The field "item" does not contain a value

I encountered a JSONException with the message "No value for {"username":"sara"}{"username":"john"}" when trying to retrieve data from a MySql database using an Android app. 08-20 04:26:39.396: W/System.err(4732): org.json.JSONException: No value for {" ...

(React Native) Creating a visually appealing grid layout for displaying an array of item cards

I am working with two arrays named 'word' and 'definition' export default class Dictionary extends React.Component { constructor(props) { super(props); this.state = { word: [], definition:[], index: ...

The debate between importing images and including them inline in NextJS is a hot

When using NextJS, what sets apart importing an image from directly including it with next/image? import logo from './logo.png'; <Image src={logo} /> /* versus */ <Image src={'/logo.png'} /> (This is pseudocode meant for ...

Is it possible to combine several m3u8 files into a single m3u8 file?

I am looking to consolidate multiple m3u8 files into a single file for seamless playback in one video player. How can I achieve this without compromising the individual clips? For instance, if I have zebra.m3u8, giraffe.m3u8, and lion.m3u8 files, is it pos ...

What is the best method for extracting an array item from a delimited string?

Here is an example of a multidimensional array: array('csv'=> array('path'=>'/file.csv', 'lines'=>array('line1', 'line2', ...

Obtain access to the DOM element using template reference variables within the component

Searching for a method to obtain a reference to the DOM element for an Angular 2 component through a template reference variable? The behavior differs when working with standard HTML tags versus components. For example: <!--var1 refers to the DOM node ...

Accessing Parent and Child Values in AngularJS Selections

I am seeking advice from experts on how to achieve the following desired results: Expected workflow chart: https://i.sstatic.net/9ZmmT.png Here is the default view: https://i.sstatic.net/H6xkZ.png Scenario 1: By clicking on the number "1", all items f ...

Creating a new database row dynamically with PHP, JavaScript, and AJAX

There is a button that triggers a popup box with a textfield when clicked. Once something is entered in the textfield and the "Add" button is clicked, it should be added to the database. Currently, upon clicking "Add", data is inserted into the DB but it ...