Iterating Through Multiple Dimensions

I am facing a challenge with creating rules from three arrays that I have. The task is to generate every possible combination of entries from each array, but I am struggling with the logic required to write a function for this purpose. For example:

var array1 = [1, 2];
var array2 = [3, 4, 5];
var array4 = [6, 7, 8, 9, 10];

I would like to receive a result containing all possible combinations in the format of strings or objects. An example output could be:

var result = ["1-3-6", "2-3-6", "1,4,6"];

I have attempted using a For Loop to solve this problem, but I am unsure how to proceed. I also considered using maps, but did not find any relevant examples. The total number of combinations based on my calculations should be 84 (2 * 7 * 6) considering the number of entries in each array.

I hope this explanation is clear, though I understand it might be somewhat confusing. Additionally, I am looking for a solution using Angular JS or vanilla JavaScript if possible, but other methods are also welcome.

Answer №1

If you're seeking the combination of arrays, what you need is the Cartesian product. A useful function for this purpose can be found below:

function cartesian() {
    var result = [], args = arguments, maximum = args.length-1;
    function helper(arr, index) {
        for (var j=0, len=args[index].length; j<len; j++) {
            var copy = arr.slice(0); // clone arr
            copy.push(args[index][j]);
            if (index==maximum)
                result.push(copy);
            else
                helper(copy, index+1);
        }
    }
    helper([], 0);
    return result;
}

Several examples are available, such as:

JavaScript - Generating combinations from n arrays with m elements

Utilizing recursion:

Finding All Combinations of JavaScript array values

Cartesian product of multiple arrays in JavaScript

Dealing with multiple (N) arrays:

Combine 2 arrays into 1 in all possible ways in JavaScript

Hope this information proves to be helpful!

Answer №2

The solution lies in utilizing nested for loops

function combineArrays(arr1, arr2, arr3) {
  var length1 = arr1.length,
    length2 = arr2.length,
    length3 = arr3.length,
    i, j, k, result = [];

  for (i = 0; i < length1; i++) {
    for (j = 0; j < length2; j++) {
      for (k = 0; k < length3; k++) {
        result.push(arr1[i] + '-' + arr2[j] + '-' + arr3[k]);
      }
    }
  }
  console.log(result)
}

combineArrays([1, 2], [3, 4, 5], [6, 7, 8, 9, 10]);

Answer №3

A more refined approach:

let setOne = [1, 2]; 
let setTwo = [3, 4, 5];
let setFour = [6, 7, 8, 9, 10]; 
let finalResult = [];

for (let numOne of setOne) {
    for (let numTwo of setTwo) {
        for (let numThree of setFour) {
            finalResult.push("\""+numOne+"-"+numTwo+"-"+numThree+"\"");
        }
    }
}
alert("["+finalResult+"]");

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

Highchart in ionic 2 not displaying

https://i.sstatic.net/q2CPR.png I inserted code for a highchart on my webpage, but it's not appearing I followed instructions from this video tutorial https://www.youtube.com/watch?v=FSg8n5_uaWs Can anyone help me troubleshoot this issue? This is ...

How to test an AngularJS controller that utilizes a service which returns a promise

I am currently creating unit tests for my components. After conducting thorough research, I have come to the realization that testing components that rely on services can be quite cumbersome and may require some messy work. I am feeling unsure about the ...

Differences between addEventListener and jQuery's on method, as well as form.submit and jQuery's

I encountered a situation where callbacks registered using jQuery's on method were not being called when trying to trigger form submission with the HTML Form element object instead of jQuery. After some testing, I discovered that changing the code to ...

What strategies can be implemented to effectively share code between these two methods?

Is there a way to consolidate code shared between these two JavaScript methods? async getAllActiveRooms(ctx: ?ContextType): Promise<RoomType[]> { //log getAllActiveRooms return this.i.knex('users_rooms') .transacting(ctx ...

Using Regular expressions in JavaScript to eliminate content between two HTML comment tags

I am currently dealing with two HTML comments in this format: <!--Delete--> Blah blah blah blah <!--Delete--> I need to remove these comments, along with any characters and newlines. I am utilizing JavaScript and Grunt for this replacement ta ...

Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows: uploadForm.onsubmit = () => { const formData = new FormData(uploa ...

Error: The componentwillmount function has encountered an issue. Actions must be in the form of plain objects. For asynchronous actions, consider

Currently, I am setting up a feature to retrieve all images based on their type using redux-saga. There are two types available: kristik and motif. While implementing the kristik type, everything works smoothly and I receive successful responses. However, ...

How to access a $scope variable in the same Angular controller function from outside the function

As a newcomer to AngularJS, I have a question about accessing my $scope variable from an outside function within the same controller. How can I achieve this? Below is the code snippet: .controller('RekapCtrl', ['$scope', '$timeout ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

Do not proceed if the process has encountered a failure

Using PHP code, I have created a way for people to get in touch with me and share their opinions. Here is the PHP code snippet: <?php $to = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef9b868c848a9bc19d869b8e988a8 ...

Dynamic Selection of JSON Key-Value Pairs in React Framework

My json data structure resembles the following: { "index": 1, "ln": "27953", "name": "Product 1", "availability": { "day0726": "G", "day0727": "G", "day0728": "G", } } I am looking for a way to dynamically disp ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Using AngularJS to load a custom JavaScript file within an ng-view

In my sample project, I have utilized Angular Js for the front-end. I have developed a template and implemented dynamic loading of views based on requirements. For this application, I am utilizing angular, jquery, and cusotm js. The structure of my templat ...

Transforming a REST API get call into GraphQL

I'm currently using a REST API that accepts a code parameter, searches the database for matches, returns results if the parameter exists, and redirects users to a long_url retrieved from the database. How can I convert this functionality to GraphQL? i ...

Checking the Value of the Second Child Element Using jQuery

I am struggling with a DIV structure that looks like this: <div class="metafield_table"> <div class="metafield"></div> <div class="metafield"></div> <div class="metafield"> ...

I'm encountering an issue where I receive the error `Cannot read property 'map' of undefined` while attempting to integrate the backend with React. What could be causing this error and how

I'm currently learning React and I've been using a tutorial here to connect my database to the front end of my React application. Unfortunately, every time I try running 'npm start' at 'localhost:3000' in express-react/backend ...

assigning attributes to web addresses

Is there a way to set a style property for webpages by targeting addresses that contain /index.php/projecten/ instead of specifying each complete address in the code? Currently, I am using the following code: <ul class="subnavlist" style="display: &l ...

What is the best way to show the current date and time?

To filter out and display only the date from the array that is the largest compared to the current date, all dates are displayed. const states = States.select().exec() var curr = new Date(); for (var i = 0; i < states.length; i++) { var maxDate = ...

Exploring the capabilities of Jasmine 2.0 by testing an AngularJS factory method that returns a promise

When attempting to test a function that returns a promise, I encounter the following error: "Error: Timeout - Async callback was not invoked within the timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. " The specification I am using is as follo ...

Tips for creating a TypeScript-compatible redux state tree with static typing and immutability:

One remarkable feature of TypeScript + Redux is the ability to define a statically typed immutable state tree in the following manner: interface StateTree { readonly subState1: SubState1; readonly subState2: SubState2; ...