
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Create All Possible Unique Permutations of a String in JavaScript
Problem
We are required to write a JavaScript function that takes in a string str. Our function should create all permutations of the input string and remove duplicates, if present. This means, we have to shuffle all letters from the input in all possible orders.
Example
Following is the code −
const str = 'aabb'; const permute = (str = '') => { if (!!str.length && str.length < 2 ){ return str } const arr = []; for (let i = 0; i < str.length; i++){ let char = str[i] if (str.indexOf(char) != i) continue let remainder = str.slice(0, i) + str.slice(i + 1, str.length) for (let permutation of permute(remainder)){ arr.push(char + permutation) } } return arr } console.log(permute(str));
Output
Following is the console output −
[ 'aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa' ]
Advertisements