首页 > 解决方案 > 如何从多维数组创建不同级别的组合?

问题描述

这是一个单一的数组组合。但我想知道结合多个的最佳方法是什么?

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 阵列。

感谢您的帮助。

标签: javascriptarrayscombinationspermutation

解决方案


你的问题不是很清楚,但我想你想要这样的东西

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


推荐阅读