 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Take an array of integers and create an array of all the possible permutations in JavaScript
We are required to write a function that does the following −
- takes an array of integers as an argument (e.g. [1,2,3,4]) 
- creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 (i.e., the length of original array) 
Example
The code for this will be −
const arr = [1, 2, 3, 4]; const permute = (arr = [], res = [], used = []) => {    let i, ch;    for (i = 0; i < arr.length; i++) {       ch = arr.splice(i, 1)[0];       used.push(ch);       if (arr.length === 0) {          res.push(used.slice());       }       permute(arr, res, used);       arr.splice(i, 0, ch);       used.pop();    };    return res; }; console.log(permute(arr));  Output
And the output in the console will be −
[ [ 1, 2, 3, 4 ], [ 1, 2, 4, 3 ], [ 1, 3, 2, 4 ], [ 1, 3, 4, 2 ], [ 1, 4, 2, 3 ], [ 1, 4, 3, 2 ], [ 2, 1, 3, 4 ], [ 2, 1, 4, 3 ], [ 2, 3, 1, 4 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 2, 4, 3, 1 ], [ 3, 1, 2, 4 ], [ 3, 1, 4, 2 ], [ 3, 2, 1, 4 ], [ 3, 2, 4, 1 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ], [ 4, 1, 2, 3 ], [ 4, 1, 3, 2 ], [ 4, 2, 1, 3 ], [ 4, 2, 3, 1 ], [ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ] ]
Advertisements
 