简体   繁体   中英

How to create different level combination from multi-dimensional array?

Here is a single array combination. But I would like to know Whats the best way to combine more than one?

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"]

Update question:

The combination should be permuted in between the arrays but Not include any single array itself. I will also need to combine and permute them into 2D/3D/4D-array respectively.

Thanks for any helps.

Your question isn't very clear but I guess you want something like this

 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]))

This snippet combinates the arrays between them but not between itself, and not duplicating the groups with the same elements in different order. If you explain itself better we will help you better too:P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM