米脂
2022-10-13 10:52:09
這是一個單一的數組組合。但我想知道結合多個的最佳方法是什么?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 陣列。感謝您的幫助。
1 回答

慕容3067478
TA貢獻1773條經驗 獲得超3個贊
你的問題不是很清楚,但我想你想要這樣的東西
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
添加回答
舉報
0/150
提交
取消