generate combinations of values from multiple array javascript

Generating combinations of values from multiple array in Javascript can be done in different ways, depending on what you are trying to achieve. To get all possible combinations of multiple arrays, you can use a combination of the map and reduce methods and the Array.from() constructor. This method uses a combination of the Map and Reduce methods to create an array of arrays, containing all possible combinations of the original arrays. The reduce method combines each element of the outer array with each element of the inner array to create an array of combinations.


//Example
var arr1 = [1,2];
var arr2 = [3,4];

var combinations = Array.from(arr1.map(x => arr2.map(y => [x,y]))
  .reduce((a,b) => a.concat(b))

//combinations = [[1,3], [1,4], [2,3], [2,4]]

You can also use the forEach method to iterate through all the arrays and generate the combinations. This method involves three for loops, each one iterating through the elements of the given array. For each iteration of the loop, a new combination of elements is added to the result array.


//Example
var arr1 = [1,2];
var arr2 = [3,4];

var combinations = [];
arr1.forEach(function(item1) {
    arr2.forEach(function(item2) {
        arr3.forEach(function(item3) {
            combinations.push([item1, item2, item3]);
        });
    });
});

//combinations = [[1,3,5], [1,3,6], [1,4,5], [1,4,6], [2,3,5], [2,3,6], [2,4,5], [2,4,6]]

Finally, you can use the for...of loop to get the combinations of values from the given arrays. This loop iterates through the elements of the array and appends each element to the resulting array. This method is slightly more efficient than the previous two, as it avoids unnecessary looping.


//Example
var arr1 = [1,2];
var arr2 = [3,4];

var combinations = [];
for (let item1 of arr1) {
    for (let item2 of arr2) {
        combinations.push([item1, item2]);
    }
}

//combinations = [[1,3], [1,4], [2,3], [2,4]]

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe