Is there a simple method in JavaScript to combine, structure, and join numerous multi-dimensional arrays in a specific manner (from right to left)?

Looking for a simple solution to merge, flatten, and concatenate multiple multi-dimensional arrays in JavaScript in a specific manner (from right to left)

# Example
[['.class1', '.class2'], ['.class3', ['.class4', '.class5', ...], ['.class6'], ...]]
# OR
[['.class1', '.class2'], ['.class3', ['.class4', '.class5', ...]], ['.class6'], ...]

# Result should be
['.class1.class3.class4.class6', '.class1.class3.class5.class6', '.class2.class3.class4.class6', '.class2.class3.class5.class6', ...]

Using the reduceRight function from the underscore.js library seems like a good option, but implementing it recursively might pose a challenge.

Answer №1

If you want to handle variable length parts in an iterative and recursive way, consider using Array#forEach method in JavaScript.

This updated version can now handle nested arrays and flatten them elegantly.


                function combineArrays(arr) {
                    function combine(part, index) {
                        let temp = arr[index];

                        if (Array.isArray(temp) && temp.some(a => Array.isArray(a))) {
                            temp = combineArrays(arr[index].map(a => Array.isArray(a) ? a : [a]));
                        }

                        temp.forEach(a => {
                            let combinedPart = part.concat(a);
                            if (combinedPart.length === arr.length) {
                                result.push(combinedPart.join(''));
                                return;
                            }
                            combine(combinedPart, index + 1);
                        });
                    }

                    let result = [];
                    combine([], 0);
                    return result;
                }

                const inputArray = [
                    ['.class1', '.class2'],
                    ['.class3',
                        ['.class4', '.class5'],
                        ['.class6']
                    ]
                ];
                
                const output = combineArrays(inputArray);
                console.log(output);
            
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

var data = [['.class1', '.class2'], ['.class3', ['.class4', '.class5'], ['.class6']];

function cartesian(a, b) {                                  // calculates the cartesian product of arrays a and b
  if(!a.length) return b;                                   // if a is empty, return b
  if(!b.length) return a;                                   // if b is empty, return a
  
  return a.reduce((res, ae) => (b.forEach(be => res.push(ae + be)), res), []); // perform cartesian product for non-empty a and b
}

function combos(arr) {                                      // generates combinations from nested arrays in arr
  if(arr.every(e => !Array.isArray(e))) return arr;         // if no nested arrays found, return arr as it is

  return arr.reduce((acc, e) => {                           // calculate the cartesian product of all elements
    e = Array.isArray(e)? combos(e): [e];                   // check if current element is an array, get its combos or wrap it in an array
    return cartesian(acc, e);                               // get the cartesian product of previous elements and this element e
  }, []);
}

console.log(combos(data));

Answer №3

For those who are willing to try out lodash, a superior alternative to underscore in my opinion, the following code simplifies combining elements of a multi-dimensional array using the flattenDeep function (https://lodash.com/docs/4.17.4#flattenDeep):

function mergeArrays(arrays) {
  const flattenedArrays = arrays.map(_.flattenDeep);
  return flattenedArrays.map((arr) => arr.join(''));
}

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

The p-dialog lacks the proper styling and does not show or hide correctly

I am working on adding a feature where dragging and dropping an event in a calendar triggers a dialog box that requires the user to confirm if they want to postpone the event. However, I ran into an issue where the styling of my p-dialog is not defaulting ...

"AngularJS makes it easy for the logged-in user's information to be accessible and available across

I need to ensure that user information is accessible across all views after logging in. How can I adjust the code to be able to retrieve the pseudonym from another view? Could you provide an example as well? Below is my login controller: app.controller ...

Send the user authentication form to a different location by using an AJAX request

I am in the process of developing a .Net Web application using ASP MVC, jQuery & AJAX. Within this application, I have a list of products. When a user clicks on the detail button of a specific product, they are taken to a details view which includes an "Ad ...

Embracing the Unknown: Exploring Wildcard Values

I have a code snippet below that has a wildcard * in it. I'm looking for suggestions on how to make the * accept any number. Any thoughts on this? $('body').on('click', '.custom_295_*-row', function(){ var href = "htt ...

Monitor the user's attendance by utilizing two separate for loops

I'm currently developing an angularjs attendance tracking system and I'm facing challenges when it comes to accurately counting the number of days an employee is absent. Despite attempting to solve this issue with two nested for loops, I am still ...

Python Selenium error: NoSuchElementException - Unable to find the specified element

Coding Journey: With limited coding knowledge, I've attempted to learn through various resources without much success. Now, I'm taking a different approach by working on a project idea directly. The goal is to create a program that interacts wi ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

Creating a Recursive Facebook Page Data Scraper using Selenium and Node.js

I am trying to iterate through an array of Facebook page IDs and retrieve the code from each event page. However, I am encountering a problem where I only get the code of the last page ID in the array repeated multiple times. For example, if there are 3 ID ...

Accessing HP ALM with REST and JavaScript on a local server: A step-by-step guide

I am trying to access ALM using locally written JavaScript in the browser (IE11, Firefox) through the REST API, but I am unable to login. Below is the code snippet where I am attempting to request the LWSSO cookie with jQuery: var auth = btoa(USER+":"+PAS ...

How can I effectively run and execute JavaScript received from a Node server using Node.js?

Hey everyone, I'm just starting out with Node and I've run into a little issue that I could use some help with. Basically, I have a page at that does some stuff, and I want to connect to the node server which is located at . var server = requir ...

Using Python's for loop to iterate through a two-dimensional index

I'm facing a challenge that seems simple, but I'm struggling to figure out how to tackle it using Python. Within my Python for loop, I have a unique value defined during each iteration. Now, I want to access the value of the NEXT or PREVIOUS uni ...

How can I update jQuery CSS method on resize event?

Having trouble vertically centering a div inside the body? I've come up with a jQuery function that calculates the ideal margin-top value for achieving perfect vertical alignment. Here's how it works: Obtain container height, Get child height, ...

The callback function in AngularJS' $http is failing to trigger

$scope.submitNewUser = function() { $http({ method: 'POST', url: 'api/user/signup', data: {'user': $scope.user}, headers: {'Content-Type': ...

The options for answering (True, False, Yes, and No) are not currently visible

I am struggling with displaying buttons for "True", "False", "Yes", and "No" in an appended row. Here is the application: Application To use the application, follow these steps: 1. Open the application and click on the green plus button. A modal window ...

Elegant Modal Form Submission Using jQuery

Having trouble submitting a modal jQuery form? A code snippet was borrowed from a website with minor modifications and the JavaScript was moved to a separate file. The challenge lies in transmitting form data to a PHP script via AJAX. The serializedArray() ...

Sending data from JavaScript to PHP in the same function

Currently, I am encountering an issue related to passing JavaScript variables to PHP within the same function. Here is a snippet of my code: else if(msg_type[i] == 'code' ){ var code_action = 'test'; <?php function foob ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

"What is the best way to include additional fields within a popover in an AngularJS application

This is my code for implementing a popover using AngularJS. I am trying to figure out how to add custom styling to the popover HTML, but I am having trouble binding elements in that part of the code. <!DOCTYPE html> <html> <head> <l ...

Error: The expression #categories_id(categories) cannot be identified due to a syntax error

Trying to use the id with brackets in jQuery is resulting in an error $("#categories_id(categories)").val("hello"); Output: An error occurred: Syntax error, unrecognized expression: #categories_id(categories) ...