JSFiddle - React, Tailwind, and code Playground

by biznuge

HTML

<div id='strOut'></div>

JavaScript

$(document).ready(function(){

var words = [];
var count = 0;  //to keep a count of the iterations

//http://www.walmik.com/2013/03/rearrange-letters-of-a-word/
//function to take one letter at a time
//with each next letter, the number of permuations and combinations reduce
//needs some work to reduce redundant iterations
//call the 'rearrange' function once like this:
/*
var word = 'goal';
rearrange('', word.split(''));
*/
function rearrange(str, arr) {
  for(var i=0; i<arr.length; i++) {
    count++;
    var balanceArr = removeItemAt(arr, i);
    var word = str + arr[i] + balanceArr.join(''); 

    if(!inArray(words, word)) {
        $('#strOut').append(word+'<br/>');
       // document.write(word + '<br />');
        words.push(word);
    }
    
    //something needs to be done here in order to not have to pass parameters that can recreate existing words
    if(balanceArr.length) rearrange(str + arr[i], balanceArr);
  }
}

/*helper functions*/
function removeItemAt(arr, index) {
  //remove the item at arr[index] and return balance items in arr
  //not using splice coz that affects the original array
  var balanceArr = [];
  for(var i=0; i<arr.length; i++) {
    if(i !== index) balanceArr.push(arr[i]);
  }
  return balanceArr;
}

function inArray(arr, item) {
  //check if an item exists in an array
  for(var i=0; i<arr.length; i++) {
    if(arr[i] == item) return true;
  }
  return false;
}

var word = 'ABCDEFG';
rearrange('', word.split(''));

});