1

How can I generate in JavaScript all the different combinations between the elements of an array of strings with the following conditions:

  • The input array of strings always has different elements (no repetition);
  • A different combination is always between 2 different elements (strings);
  • The order does not matter (the combination "A" & "B" is the same as "B" & "A").

For instance, with this input array of strings:

var array = ["A", "B", "C"];

The different combinations would only be:

  • "A" & "B" ("B" & "A" is the same combination);
  • "A" & "C" ("C" & "A" is the same combination);
  • "B" & "C" ("C" & "B" is the same combination).

I pretend to use it to do something like this:

var count = 0;
for each (different combinations in input array of strings){
   console.log (item1 of combination);
   console.log (item2 of combination);
   count = count + 1;
}
console.log(count);

Thank you *

1 Answer 1

2

Something like this would work.

var arr = ["A", "B", "C"];
var count = 0;
for (var i=0; i<arr.length; i++){
   for (var j=i+1; j<arr.length; j++){
      console.log(arr[i] + arr[j]);
      count = count + 1;
   }
}
console.log(count);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you * Definitely easier than I thought

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.