

- 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
Creating 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' ]
- Related Questions & Answers
- Generating all possible permutations of array in JavaScript
- How to find all possible permutations of a given string in Python?
- All possible permutations of N lists in Python
- Python - Generate all possible permutations of words in a Sentence
- Print all permutations of a given string
- All permutations of a string using iteration?
- Print all permutations of a string in Java
- Creating permutations by changing case in JavaScript
- Print all palindrome permutations of a string in C++
- JavaScript function that generates all possible combinations of a string
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Python Program to print all permutations of a given string
- C Program to print all permutations of a given string
- Counting all possible palindromic subsequence within a string in JavaScript
- Python program to get all permutations of size r of a string
Advertisements