How to create permutations for an array using javascript

Create permutations for an array using javascript


//create permutations for elements of an array

 const permutations = (arr) => {

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

    let firstElement = arr.slice(0,1);
    let restElements = arr.slice(1);
    let restPerms = permutations(restElements);
    let allPermutations = [];
    
    restPerms.forEach( perm => {

        for( let i = 0; i <= perm.length; i++ ) {

            let withFirstPerms = [...perm.slice(0,i), firstElement, ...perm.slice(i)];
            allPermutations.push(withFirstPerms);

        }

    });

    return allPermutations.map(element => [].concat(...element));
 };

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


Leave a Comment

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