What are some techniques for generating unique level combinations from a multi-dimensional array?

How can I efficiently combine multiple arrays and permute them without including any single array itself? Additionally, I need to combine and permute them into 2D/3D/4D-arrays. Any assistance is appreciated.

var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e', 'f'];
function permutation (list, n) {
    var results = []
    function _perm (list, n, res, start) {
        if (res.length === n) {
            return results.push(res.join(','))
        }
        if (start === list.length) { return }
        _perm(list, n, res.slice(), start + 1)
        res.push(list[start])
        _perm(list, n, res, start + 1)
    }
    _perm(list, n, [], 0)
    return results.length
}
console.log(permutation(arr3, 2))  // print ["e,f", "d,f", "d,e"]

Update question:

The combination should be permuted in between the arrays but Not include any single array itself. I will also need to combine and permute them into 2D/3D/4D-array respectively.

Thanks for any helps.

Answer №1

Your question may need some clarification, but I will try to provide a solution that fits your needs.

const a = ["a", "b"]
const b = [1, 2, 3, 4]
const c = ["x", "y", "z"]

const combineArrays = arrays => {
    const combined = arrays.reduce((acc, arr) => {
        if (acc.length === 0) { 
            return arr 
        } else { 
            return combine(arr, acc) 
        }
    }, [])
    return combined
}

const combine = (arr1, arr2 = []) => {
    const combinedArrays = arr1.map((item1) => {
        return arr2.map((item2) => {
            return `${item1}, ${item2}`
        })
    })
    return [].concat.apply([], combinedArrays)
}

console.log(combineArrays([a, b, c]))

This code snippet combines arrays with each other without duplicating groups that have the same elements in a different order. If you provide more specific information, we can offer you a more tailored solution. 😊

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

What is the best way to handle multiple responses in Ajax within a single function?

Here is a simple code snippet: $.ajax({ url:'action.php', method: 'POST', data:{getcart:1}, success:function(response){ $('#getcart').html(response);//want to ...

The event was triggered, however, some sections of the code did not run

I am currently working on a project called lan-info on GitHub. Here is the code snippet that I am using: let arpSweepCommand = './arpSweep.sh'; app.get('/arp', (req, res) => { console.log('we have a working signal!'); ...

Scraping a few URLs with Javascript for Web Data Extraction

I'm struggling to retrieve data from multiple URLs and write it to a CSV file. The problem I'm facing is that the fetched data is not complete (I expect 10 items) and it's not in the correct order. Instead of getting 1, 2, 3 sequentially, I ...

Dividing the JSON dataset into smaller segments

Here is an example demonstrating how to split the JSON data: var data = [ { BankName: 'SBI', IFSC: 'SBIN0002688' }, { BankName: 'ICICI', IFSC: 'ICIC0003931', MICR: '500229094'}, { BankName: 'RBI ...

The method provided by the FullScreen API is not effective in cancelling the fullscreen mode

After testing my code in Google Chrome, I encountered the following error message: Uncaught TypeError: Object #<HTMLDivElement> has no method 'webkitCancelFullScreen' Interestingly, I also received a similar error while running the code i ...

Choose all the items that are visible in the list using Angular

If you have the following ng-repeat: <ul class="list-group"> <ng-user-item ng-repeat="user in users | filter:search" user="user" ng-if="assigned.indexOf(user.id) < 0" ng-click="selectFunction(user);"></ng-use ...

The content in tinymce cannot be edited or removed

Is there a method to prevent certain content within the tinyMCE Editor from being edited or removed? While I know that adding a class "mceNonEditable" can make a div non-editable, it can still be deleted. Is there a way to make it unremovable as well? ...

Error injecting Angular components

Here is the structure of my HTML file: <html> <head> <title>PLD Interaction pattern</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> <body ng-app="myT ...

What are some techniques for concealing a rendered element retrieved using the fetch API?

Currently, I am grappling with a coding challenge that requires me to extract data from https://jsonplaceholder.typicode.com/users using the fetch API function along with bootstrap and jquery. To display the data in a div element, I utilized the array.map( ...

Javascript callback function

Greetings everyone! I've developed a simple nodesjs server using express. The server includes a login page where users enter their credentials to be checked against an Sqlite3 DB. My concern lies in the fact that the callback function only executes on ...

Error arises when uploading csv files to Node.js with Multer due to an unexpected field presence

I'm currently working on implementing a file upload feature with the use of Node.js, Vue, and Multer. Below is the Vue.js front-end code: export default { data(){ return{ selected: "How do you want to input the data?", options: [ ...

What is the code in CodeIgniter to retrieve the string 'Sugar & Jaggery, Salt' using <a>?

Can someone please help me? I am a beginner in CodeIgniter and I am having trouble passing a URL with a string. The controller is not accepting the string as expected. How can I fix this issue? //Below is the HTML code for passing a string value index.ph ...

How can I make an HTML button the default option within a form?

Currently, I am working on an asp.net page which contains a mix of asp.net buttons and HTML input[type=button] elements. These HTML buttons are specifically used to initiate AJAX calls. My dilemma arises when the user hits ENTER - instead of defaulting to ...

Utilizing Html.BeginCollectionItem helper to pass a collection with only a glimpse of the whole picture

After seeking guidance from Stephen Muecke on a small project, I have encountered an issue. The javascript successfully adds new fields from the Partial View and connects them to the model through "temp" values set by the controller method for the partial ...

Is there a way to refine a table based on the specific rows that are chosen in ag-Grid?

Is it possible to filter a table by rows with the attribute select: true, considering that select is not part of the data but rather an attribute of RowNode? I have tried using gridApi.getSelectedNodes() as well as text and number filters, but haven' ...

Concerning Java's Map and Array functionalities

When working with Javascript, we have the ability to create statements like the one below. var f_names = { 'a' : 'Apple', 'b' : 'Banana' 'c& ...

Update the text within a table in real time by simply checking a box

I've got some data in JSON format that I've converted into an HTML table. Now, my goal is to update the text from False to True if a checkbox is checked. How can I achieve this? Below is the code used to create the HTML table: $.each(result, fu ...

Using RxJS with Angular to intercept the valueChanges of a FormControl prior to subscribing

I decided to create a new observable using the values emitted by the FormControls.valueChanges observable. This creation of the observable takes place within the ngOnInit method in the following manner: ngOnInit(): void { this.myObservable$ = combine ...

Tips for customizing the color of the current date in the angular-material datepicker

I've created a function in angular-material to disable dates two days from now, but I'm struggling to change the color of the current date if it's disabled. The issue is that when the current date is disabled, it displays in a very light blu ...

I am experiencing issues with my three.js script not functioning properly within the context of a

I have been working on implementing a raycaster function in my project that only activates when an entity is visible. To achieve this, I was advised to create a custom script for better control. I have set up all entities and their child entities to be in ...