Unnikrishnan Unnikrishnan - 1 year ago 42
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.


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download