Open In App

Find all the combinations of the array values in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

The task is to get the Cartesian product of the arrays (Finding all combinations after concatenating them). Here, 2 approaches are discussed with the help of JavaScript.

Approaches:

 Approach 1: 

  • First, declare an array of multiple arrays.
  • Recursion is used to solve the problem. The base condition is when the length of the array reduces to zero then return the string build till now. Else
  • Reduce the first array element by reduce() method and return the result returned from the recursion result (Recursion is called every time after leaving the first item of the array) plus the previous value in concatenation with every array element.
  • Return the final ans array, which contains all combinations.

Example 1: This example implements the above approach using JavaScript Aarry.reduce() method

Javascript




let arr = [
    ['m', 'n'],
    ['c'],
    ['d', 'e', 'f']
];
 
function getCombn(arr, pre) {
    pre = pre || '';
     
    if (!arr.length) {
        return pre;
    }
     
    let ans = arr[0].reduce(function (ans, value) {
        return ans.concat(getCombn(
            arr.slice(1), pre + value));
    }, []);
    return ans;
}
 
console.log(getCombn(arr));


Output

[ 'mcd', 'mce', 'mcf', 'ncd', 'nce', 'ncf' ]

Approach 2: 

  • First, declare an array of multiple arrays.
  • Recursion is used to solve the problem. The base condition is When the length of the array reduces to one then return that element of the array. Else
  • Call recursion after leaving the first element of the array and store the result in a variable(otherCases).
  • Loop through every element of the Array (otherCases) and inside every element loop through the first element of the Array(arr).
  • Concatenate every element of the Array(arr[0]) with the Array(otherCases) and push the result in the answer array.

Example 2: This example implements the above approach using recursion in JavaScript.

Javascript




// Create new array
let arr = [
    ['m', 'n'],
    ['c'],
    ['d', 'e', 'f']
];
 
// Funtion to get all combinations
function getCombn(arr) {
 
    // When array contain 1 element
    if (arr.length == 1) {
        return arr[0];
    } else {
        let ans = [];
 
        // Recur with the rest of the array.
        let otherCases = getCombn(arr.slice(1));
        for (let i = 0; i < otherCases.length; i++) {
            for (let j = 0; j < arr[0].length; j++) {
                ans.push(arr[0][j] + otherCases[i]);
            }
        }
        return ans;
    }
}
 
// Display output
console.log(getCombn(arr));


Output

[ 'mcd', 'ncd', 'mce', 'nce', 'mcf', 'ncf' ]


Last Updated : 11 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads