1

I have an array of strings, how I can make combination of elements two at a time separated by underscore.

var array = ['a', 'b', 'c']; the output should be ['a_b', 'a_c', 'b_c']

How I can do this in Javascript?

Please note that this is different from Permutations in JavaScript? since we need a combination of two and cannot be array elements cannot be replicated.

Thanks.

4
  • 5
    Can you share what you have tried so far? Commented Jun 20, 2017 at 16:23
  • 1
    what about a_a or c_b and similar combinations? Commented Jun 20, 2017 at 16:24
  • Possible duplicate of Permutations in JavaScript? Commented Jun 20, 2017 at 16:24
  • It should not combine same elements like a_a, and if b_c exist then it should not contain c_b. Commented Jun 20, 2017 at 16:27

3 Answers 3

2

You can use nested loops to achieve something like that:

var arr = ['a', 'b', 'c'];
var newArr = [];
    
for (var i=0; i < arr.length-1; i++) {        //Loop through each item in the array
    for (var j=i+1; j < arr.length; j++) {    //Loop through each item after it
        newArr.push(arr[i] + '_' + arr[j]);   //Append them
    }
}
    
console.log(newArr);

I've elected to mark this as a community post because I think a question that shows no attempt shouldn't merit reputation, personally.

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

Comments

1

A solution could be:

function combine(arr) {

    if (arr.length === 1) {
        return arr; // end of chain, just return the array
    }

    var result = [];

    for (var i = 0; i < arr.length; i++) {
        var element = arr[i] + "_";
        for (var j = i+1; j < arr.length; j++) {
            result.push(element + arr[j]);
        }
    }
    return result;
}

Comments

0

It should be an double for, something like this:

var output = [];
var array = ['a', 'b', 'c'];
    for(var i = 0; i < array.length; i++){
        for(var j = 0; j < array.length; j++) {
           output.push(array[i] + "_" + array[j]);
        }
    }

The output is:

["a_a", "a_b", "a_c", "b_a", "b_b", "b_c", "c_a", "c_b", "c_c"]

5 Comments

Please read the comments bellow the question for more details.
This does not produce the desired output
Sorry I didn't mention it in the question, it should not combine same elements like a_a, and if b_c exist then it should not contain c_b.
In that case will be useful add: if(array[i] != array[j]) before the push
This is the output: ["a_b", "a_c", "b_a", "b_c", "c_a", "c_b"]

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.