
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Creating all possible unique permutations of a string 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?
- Finding all possible combinations from an array in JavaScript
- All reverse permutations of an array using STL in C++?
- Sum of All Possible Odd Length Subarrays in JavaScript
- Finding all possible ways of integer partitioning in JavaScript
- Print all permutations of a string in Java
- Print all permutations of a given string
- All permutations of a string using iteration?
- All possible odd length subarrays JavaScript
- Print all permutations with repetition of characters in C++

Advertisements