- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- How to count the number of elements in an array below/above a given number (JavaScript)
- Shift last given number of elements to front of array JavaScript
- How to replace elements in array with elements of another array in JavaScript?
- How to find the sum of all elements of a given array in JavaScript?
- How to duplicate elements of an array in the same array with JavaScript?
- Count occurrences of the average of array elements with a given number in C++
- Program to find number of elements in all permutation which are following given conditions in Python
- Find smallest permutation of given number in C++
- How to create a string by joining the elements of an array in JavaScript?
- Count number of elements between two given elements in array in C++
- C++ program to find permutation for which sum of adjacent elements sort is same as given array
- Create empty array of a given size in JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Finding the product of array elements with reduce() in JavaScript
- Append the current array with the squares of corresponding elements of the array in JavaScript

Advertisements