Unnikrishnan Unnikrishnan - 5 months ago 25
Javascript Question

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.

Answer Source

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.