-2

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?

Mohan Rajput
  • 634
  • 9
  • 21
  • Hi there, please look at this guide [how to ask good questions](https://stackoverflow.com/help/how-to-ask). – Jan Nov 01 '18 at 04:50
  • The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Nov 01 '18 at 04:52
  • This is neither an array nor an object – brk Nov 01 '18 at 04:53
  • You have an invalid javascript construct, and want to produce an invalid javascript construct from it - good luck – Bravo Nov 01 '18 at 04:56

2 Answers2

1

What you are looking for is a permutation function in JavaScript. This blog might be helpful. Also, take a look at another StackOverflow answer.

Petar Vasilev
  • 282
  • 1
  • 11
1

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/

dixitk13
  • 523
  • 4
  • 10