
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Permutation of Array with 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 ] ]
Advertisements