How to create permutation of array with the given number of elements in JavaScript


We are required to write a JavaScript function that takes in an array of literals as the first argument and a number as the second argument.

The function should construct an array of all such arrays which have the length equal to the number specified by the second argument and contains all possible permutations of the elements of the input array.

For example −

If the input array and the number are −

const arr = ['k', 5];
const num = 3;

Then the output should be −

const output = [
   [ 'k', 'k', 'k' ],
   [ 'k', 'k', 5 ],
   [ 'k', 5, 'k' ],
   [ 'k', 5, 5 ],
   [ 5, 'k', 'k' ],
   [ 5, 'k', 5 ],
   [ 5, 5, 'k' ],
   [ 5, 5, 5 ]
];

Example

Following is the code −

const arr = ['k', 5];
const num = 3;
const allPairs = (arr = [], num) => {
   const res = [];
   if(num === 0){
      return [[]];
   }
   const subResult = allPairs(arr, num - 1);
   for(let el of arr){
      for(let sub of subResult){
         res.push([el].concat(sub));
      }
   }
   return res;
}
console.log(allPairs(arr, num));

Output

Following is the console output −

[
   [ 'k', 'k', 'k' ],
   [ 'k', 'k', 5 ],
   [ 'k', 5, 'k' ],
   [ 'k', 5, 5 ],
   [ 5, 'k', 'k' ],
   [ 5, 'k', 5 ],
   [ 5, 5, 'k' ],
   [ 5, 5, 5 ]
]

Updated on: 20-Jan-2021

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements