javascript - 如何从多维数组创建不同级别的组合?
问题描述
这是一个单一的数组组合。但我想知道结合多个的最佳方法是什么?
var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e', 'f'];
function permutation (list, n) {
var results = []
function _perm (list, n, res, start) {
if (res.length === n) {
return results.push(res.join(','))
}
if (start === list.length) { return }
_perm(list, n, res.slice(), start + 1)
res.push(list[start])
_perm(list, n, res, start + 1)
}
_perm(list, n, [], 0)
return results.length
}
console.log(permutation(arr3, 2)) // print ["e,f", "d,f", "d,e"]
更新问题:
该组合应在数组之间排列,但不包括任何单个数组本身。我还需要将它们分别组合并排列成 2D/3D/4D 阵列。
感谢您的帮助。
解决方案
你的问题不是很清楚,但我想你想要这样的东西
const a = ["a", "b"]
const b = [1, 2, 3, 4]
const c = ["x", "y", "z"]
const combinateN = arrays => {
const combN = arrays.reduce((acc, it, i) => {
if(acc.length === 0){ return it }
else{ return combinate(it, acc) }
}, [])
return combN
}
const combinate = (arr1, arr2 = []) => {
const comb2 = arr1.map((item1, i) => {
return arr2.map((item2, j) => {
return `${item1}, ${item2}`
})
})
return [].concat.apply([], comb2)
}
console.log(combinateN([a, b, c]))
此代码段组合了它们之间的数组,但不组合自身之间的数组,并且不会以不同的顺序复制具有相同元素的组。如果您更好地解释自己,我们也会更好地帮助您:P
推荐阅读
- rest - 如何向 Azure 中正在运行的 docker 容器发送 HTTP 请求
- android - Android Studio 迫使我使用 android.media import 而不是 google.play FaceDetector
- alamofire - Swift 4.2 Alamofire:调用中的额外参数“方法”
- amazon-web-services - AWS 云形成 - 使用安全组名称创建 EC2 实例
- angular - Angular6:如何将模板变量链接到服务的数组,索引在 paramMap
- python - 使用 for 和 while 循环编写素数函数的最 Pythonic 方式是什么?
- ruby-on-rails - 在 Ruby 中的表单内调用另一个控制器
- c# - 所需功能已贬值,如何使其 appium 与 Android 驱动程序一起使用?
- angular - NgbDropdown 下拉按钮的自定义箭头
- c# - 如何在 C# 中将 char 与字符串一起使用?