1

I am having difficulty getting the following concept in to code:

Let's say we are given the following array:

[
    'h1,h2',
    'span,style'
]

From this I wish to get the following output:

[
    'h1 span',
    'h1 style',
    'h2 span',
    'h2 style
]

So that we have an array of strings containing all combinations of the original array, which also respects order (so span h1 and style h2 are not valid).

To describe verbose: I have a single level array of strings which are effectively comma separated values. I wish to iterate over this array and split these strings by their comma in to a new array, and for each index in this new array build a new string which contains all the other split values from subsequent indexes in the original array.

I am having difficulty trying to program this in JavaScript. I understand that I will need some recursion, but I'm confused about how to do it. After trying various different and failing methods, I currently have this:

function mergeTagSegments(arr, i, s) {

    i = i || 0;
    s = s || '';

    if(!arr[i]) { return s; }

    var spl = arr[i].split(',');
    for(var j in spl) {
        s += spl[j] + mergeTagSegments(arr, i+1, s);
    }

    return s;

}

This also fails to work as intended.

I feel a little embarrassed that I am unable to complete what I originally thought was such a simple task. But I really hope to learn from this.

Many thanks in advance for your advice and tips.

1 Answer 1

1

Your thinking along the right lines. Recursion is definetly the way to go. I have implemented a suggested solution below, which should give you the desired output.

var values = ['h1,h2', 'span,style'];

function merge(input, index) {
    var nextIndex = index + 1;
    var outputArray = [];
    var currentArray = [];

    if(index < input.length) {
        currentArray = input[index].split(',');
    }

    for(var i = 0, end = currentArray.length; i < end; i++) {               
        if(nextIndex < input.length) {
            merge(input, nextIndex).forEach(function(item) {
                outputArray.push(currentArray[i] + ' ' + item);
            });
        }
        else {
            outputArray.push(currentArray[i]);
        }
    }

    return outputArray;
}

var output = merge(values, 0, '');
console.log(output);
Sign up to request clarification or add additional context in comments.

Comments

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.