What is the best way to iterate through arrays in javascript?

Could someone please assist me with looping through an array of variable sizes? Here is the array:

var x = [[1,2,3],[8],[10,11,12],[13]];

I am trying to create combinations in a new array. For example:

y = [[1,8,10,13],[2,8,10,13],[3,8,10,13],
[1,8,11,13],[2,8,11,13],[3,8,11,13]....]

I hope this explanation is clear. Here is what I have attempted so far:

for(var i=0; i<x.length; i++)
{
    for(var ii=0; x[i].length; ii++)
    {
        //At this point I have x[0], but each number needs to be part of a combination 
    }
}

My end goal is to create combinations across multiple lists, such as the one below with 4 lists:

1 5  8  12
2 6  11
3 9
4 10

Answer №1

This resembles the concept of a cartesian product and recursion with a single for loop can be utilized to achieve this.

var array = [[1,2,3],[8],[10,11,12],[13]];

function generateCartesianProduct(data) {
  var result = [];

  function compute(data, n, c) {
    if (n == data.length) {
      result.push(c.slice())
      return;
    }

    for (var i = 0; i < data[n].length; i++) {
      c[n] = data[n][i];
      compute(data, n + 1, c);
    }
  }

  compute(data, 0, [])
  return result
}

console.log(JSON.stringify(generateCartesianProduct(array)))

Answer №2

function generateCombinations(arr, currentIndex, currentCombo) {

    if (currentIndex == arr.length) {
        console.log(currentCombo);
        return;
    }

    for (var j = 0; j < arr[currentIndex].length ; ++j) {
        currentCombo.push(arr[currentIndex][j]);
        generateCombinations(arr, currentIndex+1, currentCombo);
        currentCombo.pop();
    }
}

generateCombinations([[1,2,3],[8],[10,11,12],[13]], 0, []);

Output :

[ 1, 8, 10, 13 ]
[ 1, 8, 11, 13 ]
[ 1, 8, 12, 13 ]
[ 2, 8, 10, 13 ]
[ 2, 8, 11, 13 ]
[ 2, 8, 12, 13 ]
[ 3, 8, 10, 13 ]
[ 3, 8, 11, 13 ]
[ 3, 8, 12, 13 ]

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

Adding values to a String[] in Android using a different class

Having an issue with adding values to my String[] array from a different class. The goal is to populate the values in my MainScreenEntered.java class from a database using MyDatabaseAdapter.java class. Seeking assistance. Thanks. Here is the code snippet ...

Do not attempt to log after tests have finished. Could it be that you overlooked waiting for an asynchronous task in your test?

Currently, I am utilizing jest in conjunction with the Vue framework to create unit tests. My test example is successfully passing, however, I am encountering an issue with logging the request. How can I resolve this error? Is there a mistake in my usage o ...

Questions about clarifying JS promises and async-await functions

After doing some reading on promises in JavaScript, I have come across conflicting information which has left me with a few basic questions. I have two specific questions that need clarification: Is it necessary for every function in JavaScript to be ca ...

Populate an ASP Form using Javascript in Android Studio

Being relatively new to Android studio, I have been experimenting with various methods but now need some assistance. I am looking to input data into an ASP.NET Website-form using Android studio. The traditional JavaScript approach does not seem to be effec ...

Top choice for removing items from a list array

Hey there, I'm working with an array of a custom type in Angular: List { task: string; id?: number; status?: boolean; } I'm trying to figure out how to delete elements where List.status == true. I've tried two methods for this. ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

execute two distinct fetch requests on the identical query outcome

Here is a query I am working with: $all = $dbh->query("SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo) FROM movimenti_carta JOIN movimenti ON movimenti_carta.movimento=movimenti.id WHERE month(data)='$mese' AND year(data)='$ ...

Issue encountered during rendering: The function used is not a filter

Everything works fine with the search filter and pagination on the initial load. However, upon clicking to go to the next page, an error occurs stating **'Error in render: "TypeError: this.tickets.filter is not a function"'**. This issue can b ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...

Is it possible to retrieve a specific item from an object in a mongo query?

When setting up a compound index like the one below db.data.ensureIndex({ userId: 1, myObject: 1 }) Will the index be used when running the following query? db.data.find({ userId: 1, myObject: { a:'test', b:'test2' } } ...

What is the best way to assign a background color to each tr element using JavaScript?

I have a list of table rows with different background colors like <tr bgcolor="#OC6110"> <tr bgcolor="#000000"> <tr bgcolor="#FFFFFF"> Is there a way to assign unique background colors to each tr element without specifying its id value ...

Encountering a problem with vis js events

While constructing a timeline in my vue.js application, I opted to utilize vis.js. Unfortunately, I encountered some issues when attempting to incorporate events. Initially, setting @drop="myDropCallback()" did not trigger the function upon dropping an ite ...

When a radio button is checked, add a class to its parent element that has a specific class assigned to it

In order to dynamically add a class to a specific div element higher up the DOM hierarchy when a radio button is clicked, I am in need of assistance. There are multiple instances of these div elements with different radio buttons, so it is crucial that on ...

Guide on testing a function with a dependency in Angular through unit testing

Attempting to dive into unit testing, I have grasped some of the basics. However, my current challenge lies in testing a method within my code. This particular method involves calling a function from oidc-client.js that handles user sign-ins. My spec fi ...

Ways to access and delete the canvas using ref steps?

Having a canvas in a react component, I utilized react refs to access the node and implemented a destroy() method. However, I encountered an error: TypeError: canvasRef.current.destroy is not a function How can we properly access the node (canvas) using r ...

Adjust the height of the list when including or excluding floated list items that are not in the final row

Within my ul are li elements with varying widths that wrap around inside a container into multiple rows. When removing an li element from the ul, I want the container's height to adjust dynamically in case a row is eliminated. If the removal happens ...

JavaScript's includes method fails to verify input against the array

Just starting out with Javascript and striving to write clean code! To test my app, I aim to have a user's name input via prompt checked against an array for validation purposes. When I hardcode the value of a variable, the includes function filters ...

"Update the label data of a node in D3.js without the need to redraw the graph

Is there a way to dynamically change the labels of nodes in an SVG graph using d3.js without having to re-render the entire graph? I want to update the data in the node labels without redrawing the entire graph each time. It appears that changing the labe ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

Develop a simple application using the MEAN stack framework

I am new to Node.js and Express and I am interested in creating a basic AngularJS application. However, I am unsure of where to begin in terms of file organization. My desired file structure is as follows: - public ----- app ---------- components -------- ...