Creating all possible unique permutations of a string in JavaScript


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.


Following is the code −

 Live Demo

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)
         let remainder = str.slice(0, i) + str.slice(i + 1, str.length)
         for (let permutation of permute(remainder)){
            arr.push(char + permutation)
   return arr


Following is the console output −

[ 'aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa' ]

Updated on: 17-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started