Unnikrishnan
Unnikrishnan

Reputation: 3303

Combining array of strings in Javascript two at a time

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.

Upvotes: 1

Views: 73

Answers (3)

Tyler Roper
Tyler Roper

Reputation: 21672

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.

Upvotes: 2

Dij
Dij

Reputation: 9808

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;
}

Upvotes: 1

Cristian Batista
Cristian Batista

Reputation: 281

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"]

Upvotes: 0

Related Questions