I have array
array_name = ['David','John','Michael'];
I want to
array_merge = ['David John Michael','David Michael John','John David Michael','John Michael David','Michael John David','Michael David John'];
How can i do?
I have array
array_name = ['David','John','Michael'];
I want to
array_merge = ['David John Michael','David Michael John','John David Michael','John Michael David','Michael John David','Michael David John'];
How can i do?
What you are looking for is a permutation function in JavaScript. This blog might be helpful. Also, take a look at another StackOverflow answer.
So I tried out a permutations function from the ref below:
let ans = []
function swap (alphabets, index1, index2) {
var temp = alphabets[index1];
alphabets[index1] = alphabets[index2];
alphabets[index2] = temp;
return alphabets;
}
function permute (alphabets, startIndex, endIndex) {
if (startIndex === endIndex) {
ans.push(alphabets.join(' '));
} else {
var i;
for (i = startIndex; i <= endIndex; i++) {
swap(alphabets, startIndex, i);
permute(alphabets, startIndex + 1, endIndex);
swap(alphabets, i, startIndex); // backtrack
}
}
}
var alphabets = ['David','John','Michael'];
permute(alphabets, 0, alphabets.length-1);
console.log(ans)
output being:
[ 'David John Michael','David Michael John', 'John David Michael', 'JohnMichael David', 'Michael John David', 'Michael David John' ]
ref: https://js-algorithms.tutorialhorizon.com/2015/11/20/generate-permutations-backtracking/