合并JavaScript数组值



假设我有三个数组,我想在JavaScript中将它们合并为一个超级阵列。我不一定知道它们的长度,是否将设置所有三个阵列。这本质上是针对过滤系统的。

因此,有一个类别数组,一个作者数组和类型数组。他们都存储了独特的键。

所以...类别可能是[Cat1,Cat2]
作者可能是[Author7,Author8]
类型可能是[Type9,Type11]

这将使另一个具有这些值的数组

[
     Cat1 Author7 Type9,
     Cat1 Author7 Type11,
     Cat1 Author8 Type9, 
     Cat1 Author8 Type 11,
     Cat2 Author7 Type9,
     Cat2 Author7 Type11,
     Cat2 Author8 Type9, 
     Cat2 Author8 Type 11,
]

因此,从阵列中可能的组合也是如此。有时,一个或两个阵列可能是空的。我可以创建一堆IF语句,但必须有更好的方法。

非常感谢。

您只需要3个嵌套foreach()循环:

var cat = ["Cat1","Cat2"];
var author = ["Author7","Author8"];
var type = ["Type9","Type11"];
var result = []
cat.forEach(x => author.forEach(y => type.forEach(z => result.push(x.concat(y).concat(z)))));
console.log(result);
如果类型为空:

var cat = ["Cat1","Cat2"];
var author = ["Author7","Author8"];
var type = [];
var result = []
cat.forEach(x => author.forEach(y => type.length === 0 ? result.push(x.concat(y)) : type.forEach(z => result.push(x.concat(y).concat(z)))));
console.log(result);

最新更新