How to create combinations of an array using javascript?

Create combinations of an array using javascript


//combinations

const combinations = (arr) => {

    if(arr.length === 0) return [[]];

    let firstElement = arr[0];
    let restElements = arr.slice(1);

    //recursive call
    let combinationsWithoutFirstElement = combinations(restElements);
    let combinationsWithFirstElement = [];

    combinationsWithoutFirstElement.forEach(comb => {
        let combinationWithFirst = [...comb, firstElement];
        combinationsWithFirstElement.push(combinationWithFirst);

    }); 
    
    //combine first and rest of the combination
    return [...combinationsWithoutFirstElement, ...combinationsWithFirstElement];
}


console.log(combinations(['a', 'b', 'c']);

Leave a Comment

Your email address will not be published. Required fields are marked *