A step-by-step guide on generating all possible combinations of elements within a nested array

I am working with an array of arrays in TypeScript and I want to perform a specific action on every possible permutation of elements between the inner arrays.

For example:

const arrOfArrays = [
    [1],
    [2, 3, 4],
    [5, 6],
    [7, 8]
];

recursePermutations(arrOfArrays, permutation => {
    console.log(permutation);
});

When this code is executed, the desired output should be as follows:

[ 1, 2, 5, 7 ]
[ 1, 2, 5, 8 ]
[ 1, 2, 6, 7 ]
[ 1, 2, 6, 8 ]
[ 1, 3, 5, 7 ]
[ 1, 3, 5, 8 ]
[ 1, 3, 6, 7 ]
[ 1, 3, 6, 8 ]
[ 1, 4, 5, 7 ]
[ 1, 4, 5, 8 ]
[ 1, 4, 6, 7 ]
[ 1, 4, 6, 8 ]

The callback for permutations should be called with the number of elements equal to the non-empty inner arrays present.

While there are questions on how to find permutations within a fixed number of arrays, my scenario involves an unknown number of inner arrays.

Answer №1

Exploring a recursive and generic approach, this solution tackles permutations:

function generatePermutations<T>(arrays: T[][], callback: (permutation: T[]) => void, index: number = 0, previousElements: T[] = []) {
    if (index < arrays.length) {
        const currentElements = arrays[index];
        for (var element of currentElements) {
            generatePermutations(arrays, callback, index + 1, previousElements.concat(element));
        }
        if (currentElements.length < 1) {
            generatePermutations(arrays, callback, index + 1, Array.from(previousElements));
        }
    }
    else if (previousElements.length > 0) {
        callback(previousElements);
    }
}

This solution accounts for scenarios where the outer array lacks inner arrays by skipping the callback.

If any of the inner arrays are empty, the permutation callback is still triggered with the non-empty inner arrays.

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

When applying Bucket Sort to an array sorted in reverse order, the program encounters an ArrayIndexOutOfBoundsException

In order to run an array that is sorted in reverse order (e.g. 100, 99, 98, 97...3, 2, 1, 0 - highest to lowest) through a bucket sort that will rearrange it from lowest to highest, the following code is used: int n = 100; // Determines the size of the arr ...

What is the best way to fetch data before a component is rendered on the screen?

I am facing an issue with fetching data from a local server in Node. When I try to render the component, the array 'users' from the state appears to be empty, resulting in no users being displayed on the screen as intended. What's strange is ...

Choice of product variations as a package

I am currently working on a project and here is the data structure I have set up for options and combinations: https://i.sstatic.net/K2utM.gif Options: "options": [ { "id": "96ce60e9-b09b-4cf6-aeca-83f75af9ef4b", "posit ...

Rotating arrays to the left in Java

For a given array of integers and a specific number, the task at hand is to carry out left rotations on the array and then provide the updated array in the form of a single line of space-separated integers. I have successfully passed 7 out of 9 checks, but ...

Angular 5 is throwing an error stating that it cannot read the property 'text' of undefined

I have developed a question component where I have added some predefined questions. However, when I attempt to execute the application, it displays 'undefined' text. Below is my component code: import { Component, OnInit } from '@angular/c ...

Is it necessary for the version of the @types packages in TypeScript to match their non-types packages?

Are @types and untyped packages versioned the same way? npm i bluebird @types/bluebird -S returns "@types/bluebird": "^3.5.0", "bluebird": "^3.5.0", This seems logical. npm i request @types/request -S yields "@types/request": "0.0.41", "request": "^2. ...

Redis is prepared and awaiting authorization for authentication. ReplyError: NOAUTH Authentication needed

When attempting to connect to a Redis instance hosted on redislab, an error message is received indicating Redis ready ReplyError: NOAUTH Authentication required. const pubClient = createClient({ url: `${config.redisLabHost}:${config.redisLabPort}` }); pub ...

Discover the step-by-step process for moving data between collections in MongoDB

I am currently working on nestjs and have two collections, one for orders and the other for payments. My goal is to retrieve a single entry from the orders collection and save that same entry into the payments collection. Below is the code for the service ...

Tips for transforming my JSON format into the necessary column layout for C3.js

The data structure returned by my API is as follows. However, I need to reformat this structure for use in C3.js. { "data":{ "test7":[ { "Date":"2016-04-26 00:00:00", "aId":7, "Amount":436464, "Piece":37 ...

Encountering Next.js Hydration Issue when Using Shadcn Dialog Component

While working on a Next.js project, I came across a hydration error when utilizing the Shadcn Dialog component. The specific error message reads: "Hydration failed because the initial UI does not match what was rendered on the server." Highligh ...

What is the most efficient way to remove multiple items from an array based on their value?

My goal is to create a function called removeAll() that will eliminate all elements of an array with a specific value, rather than based on index. The challenge arises when any modifications are made to the loop, causing the indexes to shift (which makes ...

Generate an array of decimal numbers decrementing from the highest value to 0

I have a JavaScript/jQuery function that generates values, typically around 0.12 or 0.25. My goal is to create an array with approximately 10 values where the initial value is either at the beginning or end of the array, and then gradually decrease to 0. ...

Use the blacklist array to replace entire words instead of just portions of the words

I currently have an array filled with various words $banned_names = array('about','access','account'); Although the actual array is extensive and contains inappropriate terms, I'm just providing a limited example to avoi ...

Exploring the method of utilizing foreach loop for handling AJAX arrays within Laravel

Looking for a solution regarding an ajax function that involves posting multiple files in an array. I encountered an issue where only the first file is being stored when trying to save them using the code snippet below: foreach ($request->photos as $ima ...

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Transform Dynamic Array to JSON structure

I am currently developing a feature in my SvelteKit application that allows users to create custom roles for themselves. Users can input a role name and add it to an array, which is then displayed below. https://i.stack.imgur.com/oUPFU.png My goal is to ...

Adding a new field to the first position in an array object using PHP CodeIgniter

How can I update the value in $row['data'] if it is currently empty? $row['data'] = $this->Employee_model->GetEmployeeRecord($id); if(empty($row['data'])){ } ...

Kindly describe the function below that calculates the size of an array

Is this a Duplicate? What does this template code do that provides the size of an array? template <typename T,unsigned S> unsigned GetArraySize(const T (&v)[S]) { return S; } I grasp the concept of T and S, but I'm puzzled by ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...