Open In App

Find all the combinations of the array values in JavaScript

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: 

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






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: 

Example 2: This example implements the above approach using recursion in 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' ]

Article Tags :