Concatenating two or more arrays in Javascript

I currently have a Javascript array of unknown length containing arrays of (unknown length) strings. I am looking for a way to find all possible combinations using one string from each second level array. Note: the order of the lines does not matter. That is, for:

[
    [
        'a',
        'b'
    ],
    [
        'c',
        'd'
    ]
]

      

I would like to return:

[
    'ac',
    'ad',
    'bc',
    'bd'
]

      

or if:

[
    [
        'a',
        'b'
    ],
    [
        '1'
    ],
    [
        'i',
        'j',
        'k',
    ]
]

      

I would like to return:

[
    'a1i',
    'a1j',
    'a1k',
    'b1i',
    'b1j',
    'b1k',
]

      

It seems to me that the answer lies in the recursive function, however I can't seem to get it to work (the variable scope gets confusing and it just falls flat).

Instead, I tried a different way of creating an array of results, looping through each subarray and placing each row in the results so that every possible combination was created:

function getArrayStrings(allTerms){

    // get total number of possible combinations
    var numberOfElements = 1;

    $.each(allTerms, function(index, element){
        numberOfElements *= element.length;
    });


    // create array of results
    var result = [];

    for(i = 0; i < numberOfElements; i ++){
        result[i] = '';
    }

    // instantiate variables that will be used in loop
    var elementToUse = 0;
    var currentLength = 1;
    var prevLength = 1;

    // for each array, loop through values and add them to the relevant result element
    $.each(allTerms, function(index, array){    

        // find length of current array
        currentLength = array.length;
        elementToUse = 0;

        // for each of the elements in the results array
        for(i = 0; i < numberOfElements; i ++){

            // change the element to use if you've looped through the previous length (but not if it first result
            if(i !== 0 && i % prevLength === 0){
                elementToUse ++;
            }

            // return to using the first element if you've reached the last element in the sub array
            if(elementToUse % currentLength === 0){
                elementToUse = 0;
            }

            result[i] += '.' + array[elementToUse];

        }

        prevLength = array.length * prevLength;

    });

    console.log(result.join(''));

    return result.join('');

}

      

This does work, however I wondered if anyone knew of a simpler function; I feel like this is what the Javascript (or jQuery) function already has, but I can't seem to find it.

Has anyone faced such a problem before? And if so, how did you approach him?

+3


source to share


3 answers


Simple recursion:

    var a = [ [ 'a', 'b' ],
              [ '1' ],
              [ 'i', 'j', 'k' ]
    ];

    function combo( arr, i, j ) {
        if (i===j-1) return arr[i];   
        var res = [];
        arr[i].forEach( function(a) {
            combo( arr, i+1, j ).forEach( function(b) {
                res.push(a+b);
            });
        });
        return res;
    }

    console.log( combo(a, 0, a.length) );

      



http://jsfiddle.net/zpg04kso/1/

+1


source


I took advantage of the fact that you can combine auxiliary arrays in pairs. It seems a little more straightforward to me.

var input = [
    ['a','b'],
    ['1', '2','3','4'],
    ['i','j','k']
];

function getArrayStrings(input) {    
    function combine(arr1, arr2) {
        var output = [];
        for (var i=0;i<arr1.length;i++) {
            for(var j=0;j<arr2.length;j++) {
                 output.push(arr1[i] + arr2[j]);
            }
        }
        return output;
    }

    var output = [];
    for(var i=0;i<input.length;i++) {
        if (i==0) output = input[i];
        else output = combine(output, input[i]);
    }

    return output;
}

var output = getArrayStrings(input);
console.log(output);

      



http://jsfiddle.net/blaird/kcytLv1r/

0


source


It works.

var a = [['a','b'], ['1'],['i','j','k']],
        b = [];


function cat(a1,a2){
    var a = []
            l = undefined;

    while (a2.length > 0){
        l = a2.shift();
        a1.forEach(function(ele,idx,arr){
            a.push(ele + l)
        })
    }
    return a;
}

function merge(arr){
    if (arr.length == 1){
        return arr.shift()
    } else {
        var a1 = arr.shift()
        return cat(a1,merge(arr))
    }
}


var b = merge(a);
console.log(b)

      

0


source







All Articles