Skip to content
the poor coder

generate combinations of values from multiple array javascript

Poor Man
Published
Reading time
2 min read

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.

JavaScript

//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.

JavaScript

//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.

JavaScript

//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]]

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC