

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 ] ]
- Related Questions & Answers
- Shift last given number of elements to front of array JavaScript
- How to count the number of elements in an array below/above a given number (JavaScript)
- Find smallest permutation of given number in C++
- Count occurrences of the average of array elements with a given number in C++
- How to replace elements in array with elements of another array in JavaScript?
- Program to find number of elements in all permutation which are following given conditions in Python
- How to duplicate elements of an array in the same array with JavaScript?
- Count number of elements between two given elements in array in C++
- Create empty array of a given size in JavaScript
- Find the Number of permutation with K inversions using C++
- Append the current array with the squares of corresponding elements of the array in JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Finding the product of array elements with reduce() in JavaScript
- Possible number of Rectangle and Squares with the given set of elements in C++
- Count of matrices (of different orders) with given number of elements in C++
Advertisements