对于数组中的每三个项,连接另一个数组

时间:2017-05-14 09:54:49

标签: javascript arrays

我正在尝试使用Javascript从一个已连接到另一个数组的字符串的数组中获取所有主题的列表。 例如:

var Alevels = ["Accounting", "Arts, Crafts and Design", "Biology", 
    "Chemistry", "Classical Civilisation", "Computer Science", "Dance"];

var Degrees = ["Animal Conservation", "Business", "Business and Management",
    "Business and Computing","Business with Events Management","Computing",
    "Digital Technology","Early Childhood Studies","electronics and Communications"];

我想让Javascript做的是从Alevels数组中选择三个值,然后从Degrees数组中选择一个并将值连接在一起,而不是以不同的顺序显示相同的字符串这样:

var string = AlevelValue1 + " - " + AlevelValue2 + " - " + AlevelValue3 + " 
    = " + degreeValue;

目前我有以下代码,但这只需要Alevels列表中的一个值和Degrees列表中的一个值:

for (let value1 of Alevels) {
    for (let value2 of Degrees) {
        var div = document.createElement('li');
        div.innerHTML = value1 + " - " + value2;
        Table.appendChild(div);
    }
}

任何帮助都会非常感激!

非常感谢

2 个答案:

答案 0 :(得分:0)

像这样?始终有三项<ee:cache doc:name="Cache" cachingStrategy-ref="Caching_Strategy"> <!-- flow --> </ee:cache> ,另外一项来自Alevels。我假设给定的顺序是正确的。

Degrees

答案 1 :(得分:0)

一种简单的方法是计算3个Alevels的所有组合,然后将所有度数连接到这些组合上。

var Alevels = ["Accounting", "Arts, Crafts and Design", "Biology", 
    "Chemistry", "Classical Civilisation", "Computer Science", "Dance"];

var Degrees = ["Animal Conservation", "Business", "Business and Management",
    "Business and Computing","Business with Events Management","Computing",
    "Digital Technology","Early Childhood Studies","electronics and Communications"];
    
function getCombinations(array, length) {
    function fork(i, t) {
        if (t.length === length) {
            result.push(t);
            return;
        }
        if (i === array.length) {
            return;
        }
        fork(i + 1, t.concat([array[i]]));
        fork(i + 1, t);
    }

    var result = [];
    fork(0, []);
    return result;
}

var aLevelCombinations = getCombinations(Alevels, 3);
var finalCombinations = [];

for (var i = 0; i < Degrees.length; i++) {
    for (var j = 0; j < aLevelCombinations.length; j++) {
      var newList = [].concat(aLevelCombinations[j]).join(' - ');
      newList = newList + ' = ' + Degrees[i];
      finalCombinations.push(newList);
    }
}

console.log(finalCombinations);