简体   繁体   English

在尊重顺序的同时递归构建所有可能组合的 JavaScript 数组

[英]Recursively constructing a JavaScript array of all possible combinations while respecting order

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).这样我们就有了一个包含原始数组的所有组合的字符串数组,它也遵守顺序(因此span h1style h2无效)。

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.我在尝试用 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.非常感谢您的建议和提示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM