What is the best way to combine multiple arrays in JavaScript?

I am working with multiple arrays:

 var array1 = [a,b,c];
 var array2 = [c,d];
 var array3 = [e,f];

I need to combine these arrays into one merged array, with the desired output as follows:

result = [ace, acf, ade, adf, bce, bdf, bde, bdf, cce, ccf, cde, cdf]

Is there a way to achieve this? Keep in mind that the number of input arrays can vary.

Answer №1

An iterative and recursive method can be utilized in conjunction with a combination algorithm.

function combine(array) {
    function combineParts(part, index) {
        array[index].forEach(function (a) {
            var newPart = part.concat([a]);
            if (newPart.length === array.length) {
                result.push(newPart.join(''));
                return;
            }
            combineParts(newPart, index + 1);
        });
    }

    var result = [];

    combineParts([], 0);
    return result;
}

console.log(combine([['a', 'b', 'c'], ['c', 'd'], ['e', 'f']]));
console.log(combine([['a', 'b', 'c'], ['d', 'e'], ['f', 'g'], ['h', 'i', 'j']]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Optimize your code with nested loops Check out the Jsfiddle example here

var array1 = ["a", "b", "c"];
var array2 = ["c", "d"];
var array3 = ["e", "f"];
var result = [], pushresult = 0;

for (var i = 0; i < array1.length; i++) {
  for (var j = 0; j < array2.length; j++) {
    for (var k = 0; k < array3.length; k++) {
      pushresult = array1[i] + array2[j] + array3[k];
      result.push(pushresult);
    }
  }
}

console.log(result);

Answer №3

It appears that you are attempting to generate the Cartesian product from multiple arrays or sets.
Here is a solution in ES6 utilizing Array.concat, Array.reduce, and Array.map functions:

const flatten = (arr) => [].concat.apply([], arr);
const product = (...sets) =>
    sets.reduce((acc, set) =>
            flatten(acc.map(x => set.map(y => [ ...x, y ]))),
    [[]]);

var array1 = ['a', 'b', 'c'],
    array2 = ['c','d'],
    array3 = ['e','f'];

result = product(array1, array2, array3);

console.log(JSON.stringify(result));

Answer №4

When dealing with a fixed number of arrays (not elements within the array), you have the option to implement the following JavaScript code:

<script>
var firstArray = ["apple", "banana", "cherry"];
var secondArray = ["cherry", "date"];
var thirdArray = ["elderberry", "fig"];
var combinedArray = [];

for (i in firstArray) {
    for (j in secondArray) {
        for (k in thirdArray) {
            combinedArray.push(firstArray[i] + secondArray[j] + thirdArray[k]);
        }
    }
}

alert(combinedArray);
</script>

Answer №5

Looking for a solution to find the cross-product of an unknown number of arrays? Here's how you can achieve it:

Array.prototype.cartesian = function(...a){
  return a.length ? this.reduce((p,c) => (p.push(...a[0].cartesian(...a.slice(1)).map(e => a.length > 1 ? [c,...e] : [c,e])),p),[])
                  : this;
};

var arr1 = ["a","b","c"],
    arr2 = ["c","d"],
    arr3 = ["e","f"],
  result = arr1.cartesian(arr2,arr3);
console.log(JSON.stringify(result));

Answer №6

Utilizing the List applicative and monad makes this task a breeze

// Implementing Array Applicative  
Array.prototype.ap = function ( ...args )
  {
    const loop = ( acc , [ x , ...xs ] ) =>
      x === undefined
        ? [ this [ 0 ] ( ...acc ) ]
        : x.chain ( a =>
            loop ( acc.concat ( [ a ] ) , xs ) )
    return loop ( [] , args )
  }
 
// Implementing Array Monad
Array.prototype.chain = function chain (f)
  {
    return this.reduce ( ( acc , x ) =>
      acc.concat ( f (x) ), [] )
  }

// Utilizing the implemented functions
const combinations = ( ...xxs ) =>
  [ ( ...xs ) => xs ] .ap ( ...xxs )

console.log ( combinations ( array1 , array2 , array3 ) )
// [ [ 'a1', 'a2', 'a3' ],
//   [ 'a1', 'a2', 'b3' ],
//   [ 'a1', 'a2', 'c3' ],
//   [ 'a1', 'b2', 'a3' ],
//   [ 'a1', 'b2', 'b3' ],
//   [ 'a1', 'b2', 'c3' ],
//   [ 'b1', 'a2', 'a3' ],
//   [ 'b1', 'a2', 'b3' ],
//   [ 'b1', 'a2', 'c3' ],
//   [ 'b1', 'b2', 'a3' ],
//   [ 'b1', 'b2', 'b3' ],
//   [ 'b1', 'b2', 'c3' ],
//   [ 'c1', 'a2', 'a3' ],
//   [ 'c1', 'a2', 'b3' ],
//   [ 'c1', 'a2', 'c3' ],
//   [ 'c1', 'b2', 'a3' ],
//   [ 'c1', 'b2', 'b3' ],
//   [ 'c1', 'b2', 'c3' ],
//   [ 'd1', 'a2', 'a3' ],
//   [ 'd1', 'a2', 'b3' ],
//   [ 'd1', 'a2', 'c3' ],
//   [ 'd1', 'b2', 'a3' ],
//   [ 'd1', 'b2', 'b3' ],
//   [ 'd1', 'b2', 'c3' ] ]

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

Receiving a blank request payload despite implementing a body parsing middleware

I am currently working on setting up a login system, and I have a form that sends a post request to my webpack dev server. This server then proxies the request to my actual server. Here is the function responsible for handling the form submission and send ...

Encountering issues with reading undefined properties while working with react-chartjs-2 and chart js

Having trouble with react chartjs errors? Visit the link for more details https://i.stack.imgur.com/lI2EP.png The versions I'm using are ^3.5.0 for chart.js and ^4.0.1 for react-chartjs-2 Tried downgrading to version 2 but it didn't solve the ...

Storing binary data uploaded via AJAX in PHP on the server is essential for maintaining

I successfully imported a .png image file as an Array Buffer. var readSingleFile = function(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); ...

AngularJS view fails to reflect updates in the model

This issue with Angular has been widely discussed online, but I ask for your patience. I have tried various solutions without success. Here is a simplified version of my code: View: <div ng-hide="{{beHidden}}"></div> Controller: // Set beHi ...

Instructions on allowing the user to enter text for searching through an array of objects, and displaying a message if a match is found. Use only pure JavaScript

As a newcomer to JavaScript, I greatly appreciate the support from everyone on this platform. Thank you in advance for your help! I am currently working on building a basic music app as a learning project in JavaScript. The main goal is to understand how J ...

Two DIV elements are merging together with a cool zooming effect

As a beginner in using Bootstrap 4, I am working on creating a practice website. While designing the layout, I encountered an issue that seems simple but I can't seem to figure it out. <div id="box-container" class="container-fluid"> &l ...

Implementing form validations using JavaScript for a form that is created dynamically

I have dynamically created a form using javascript and now I need to add mandatory validations on the form. The validations should trigger when the dynamically created button is clicked. However, I am facing an issue where I receive an error whenever I t ...

Calling Functions in JavaScript Through Events: A Beginner's Guide

As I dive into learning JavaScript, one thing that stumps me is figuring out how to call a function from an event. Currently, the only method I am familiar with involves using anonymous functions (as seen in my code example below), but I'm curious if ...

The SEMrush API is not displaying an 'Access-Control-Allow-Origin' header on the requested resource

When attempting to utilize the SEMrush API, I made a request using jQuery as shown below: $(document).ready(function() { $.get( 'https://api.semrush.com', { type: 'phrase_this', key: ' ...

Issue: ui-route failing to function properly when the href attribute is utilized

I am currently working on implementing ui-route to manage the states of my app while focusing on URL navigation. My goal is to enable users to simply click on a link and be directed to the state associated with the specific URL. After following an In-Dep ...

Utilize Devextreme's dxDataGrid component to transmit the selected RowData to a function upon clicking a button within that particular row

I am utilizing the dxDataGrid user interface widget from the Devextreme product. My goal is to transform one of its columns into a clickable button. Here is my progress so far: Field Configuration { dataField: 'LetterNumber', caption: ' ...

store the id of each li element dynamically into an array

In my code, a list is generated dynamically and each list item has a special id. I am trying to store each li "id" in one array. This is JavaScript code: var i = 0; $("ul#portfolio li").each(function(eval) { var idd = new Array(); idd[i] = $(this ...

Unable to locate the AngularJS controller after attempting to paste the code

Currently enrolled in the AngularJS Mastery Course on Udemy, I encountered an odd issue that has left me scratching my head. The code provided seems to function flawlessly for most users, except for a select few. index.html <html lang="en" ng-app=&apo ...

When attempting to start a new React Native project using npx, I encountered an error stating "react-native: command not found"

After running 'npx react-native init MyProject' for the first time, it prompted that react-native would be downloaded, but I mistakenly terminated the process. Now, when I try again, it shows an error saying 'react-native: command not found& ...

Is there a way to ensure the content of two divs remains aligned despite changing data within them?

Currently, I have two separate Divs - one displaying temperature data and the other showing humidity levels. <div class="weatherwrap"> <div class="tempwrap" title="Current Temperature"> ...

Creating SVG paths using coordinates for THREE.js

I copied the exact code from this ThreeJs Example designed for generating a three-dimensional City Model. I've created an SVG path outlining city boundaries using Google Maps and now I'm trying to use the above code to create a similar 3D object ...

Find the element that was not included in the array

Having to deal with an array, I encountered a dilemma. The array looks something like this: public static int getMissed(int[] array) {...} For instance, the array is {1,3,5,7,11}. Clearly, the 4th element is missing, which should have been 9. Considerin ...

Why was the express.js boilerplate code created?

As a newcomer to Node and Express, I am curious about the purpose of the boilerplate directories that are automatically generated when setting up an express project. I have searched online for explanations on the significance of these files without much l ...

Receiving encoded characters in the response

URL: I have encountered an issue where I am trying to retrieve the PDF file from the URL above using code. In tools like Postman or Insomnia, I am able to see the output as expected in PDF format. However, when I attempt it with code, I am receiving rando ...

Is there a way to substitute the HOC with a single call and solely modify the prop?

One issue I've encountered in my project is the repetitive use of a Higher Order Component (HOC) for the header. Each time it's used, the props are set to determine whether header links should be displayed or not. My objective is to streamline th ...