-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?

4
  • Hi there, please look at this guide how to ask good questions. Commented Nov 1, 2018 at 4:50
  • The posted question does not appear to include any attempt at all to solve the problem. StackOverflow expects you to try to solve your own problem first, 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 minimal reproducible example. For more information, please see How to Ask and take the tour. Commented Nov 1, 2018 at 4:52
  • This is neither an array nor an object Commented Nov 1, 2018 at 4:53
  • You have an invalid javascript construct, and want to produce an invalid javascript construct from it - good luck Commented Nov 1, 2018 at 4:56

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.