

- 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
Generating all possible permutations of array in JavaScript
We are given an array of distinct integers, and we are required to return all possible permutations of the integers in the array.
For example −
If the input array is −
const arr = [1, 2, 3];
Then the output should be −
const output = [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ];
Example
The code for this will be −
const arr = [1, 2, 3]; const findPermutations = (arr = []) => { let res = [] const helper = (arr2) => { if (arr2.length==arr.length) return res.push(arr2) for(let e of arr) if (!arr2.includes(e)) helper([...arr2, e]) }; helper([]) return res; }; console.log(findPermutations(arr));
Output
And the output in the console will be −
[ [ 1, 2, 3 ], [ 1, 3, 2 ], [ 2, 1, 3 ], [ 2, 3, 1 ], [ 3, 1, 2 ], [ 3, 2, 1 ] ]
- Related Questions & Answers
- Creating all possible unique permutations of a string in JavaScript
- Take an array of integers and create an array of all the possible permutations in JavaScript
- All possible permutations of N lists in Python
- Python - Generate all possible permutations of words in a Sentence
- Finding all possible subsets of an array in JavaScript
- How to find all possible permutations of a given string in Python?
- All reverse permutations of an array using STL in C++?
- Finding all possible combinations from an array in JavaScript
- Print all permutations of a given string
- All permutations of a string using iteration?
- Print all permutations of a string in Java
- Finding all possible ways of integer partitioning in JavaScript
- Sum of All Possible Odd Length Subarrays in JavaScript
- All possible odd length subarrays JavaScript
- Print all permutations with repetition of characters in C++
Advertisements