I\'m trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting wit
This is usiing loop as you expected easiest way.. good luck
function mixString() {
var inputy = document.getElementById("mixValue").value
var result = document.getElementById("mix-result")
result.innerHTML=""
for (var i = 0 ; i < inputy.length; i++) {
for (var b = 0 ; b < inputy.length; b++) {
if (i == b) {
result.innerHTML += inputy.charAt(i) + ","
}
else
{
result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
}
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">JavaScript string combination
</div>
<div class="panel-body">
<input id="mixValue" class="form-control" />
<input type="button" onclick="mixString()" value="click" />
<div id="mix-result"></div>
</div>
</div>
</div>
The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.
// however, we don't want duplicates so...
if (!result.includes(next)) {
result.push(next);
}