用js循环如何得出该结果?

我有一个数组,结构如下:

let arr = [

{tag:['A','B']},

{tag:['C','D']},

{tag:['E','F']}

]

arr的长度不一定
如何让它输出如下结果?
A,C,E
A,C,F
A,D,E
A,D,F
B,C,E
B,C,F
B,D,E
B,D,F


回答:

js">function transform(list) {

var ret = [];

return (function collect(depth, cache) {

var tag = list[depth++].tag;

for (var i = 0; i < tag.length; ++i) {

var arr = cache.concat([tag[i]]);

if (depth < list.length) {

collect(depth, arr);

} else {

ret.push(arr);

}

}

return ret;

})(0, []);

}

console.dir(transform(arr));


回答:

学会使用reduce

arr.reduce((res, item) => {

return res.length ? res.reduce((nres, cres) => {

return nres.concat(item.tag.map(c => [...cres, c]))

}, []) : item.tag.map(citem => [citem])

}, [])


回答:

let arr = [

{tag:['A','B']},

{tag:['C','D']},

{tag:['E','F']}

]

let list1=arr[0].tag

let list2=arr[1].tag

let list3=arr[2].tag

list1.forEach(val1=>{

list2.forEach(val2=>{

list3.forEach(val3=>{

console.log(`${val1},${val2},${val3}`)

})

})

})


回答:

这个问题我翻译一下,实际上是有多个二元对象的序列数组,按序生成全排列的算法。
如果每个tag都是2个元素的数组,这个问题可以简化用位运算直接输出,结果数量就是N位二进制的有序数列。
当然这个算法在javascript可能需要用到bigint,否则数量受到限制,不过我想这个数组不可能太长,否则计算机也吃不消的。

var getA=function(inX,list,len){

let rt=[];

for(let i=0;i<len;i++){

rt.push( list[i]["tag"][ (inX>>(len-i-1)) & 1 ])

}

return rt.join(',');

}

var transform=function(list){

var rt = [];

let len=list.length;

let end=1<<len;

for( let i=0;i<end;i++ ){

rt.push( getA(i,list,len) )

}

return rt;

}

let arr = [

{tag:['A','B']},

{tag:['C','D']},

{tag:['E','F']},

{tag:['G','H']},

{tag:['I','J']},

{tag:['K','L']},

{tag:['M','N']},

{tag:['O','P']},

{tag:['Q','R']},

{tag:['S','T']},

{tag:['U','V']},

{tag:['W','X']},

{tag:['Y','Z']},

{tag:['a','b']},

{tag:['c','d']},

{tag:['e','f']},

{tag:['g','h']},

{tag:['i','j']},

{tag:['k','l']},

{tag:['m','n']}/*, 试了下,这里都要好几秒才能算出来啦,这里就有上100万输出啦!

{tag:['o','p']},

{tag:['q','r']},

{tag:['s','t']},

{tag:['u','v']},// 这个算法可以计算到这么多,大概15秒,更多在chrome中报错。

{tag:['w','x']},

{tag:['y','z']}

//*/

]

console.dir(transform(arr));


回答:

抄改一个:

const arr = [

['A','B'],

['C','D'],

['E','F'],

['G','H'],

['I','J'],

['K','L'],

['M','N'],

['O','P'],

['Q','R'],

['S','T'],

['U','V'],

['W','X'],

['Y','Z'],

['a','b'],

['c','d'],

['e','f'],

['g','h'],

['i','j'],

['k','l'],

['m','n'],

// ['o','p'],

// ['q','r'],

// ['s','t'],

// ['u','v'],

// ['w','x'],

// ['y','z'],

]

/**

*

* @param {string[][]} arr

*/

const arrange = (arr) => {

const result = []

const hex = arr[0].length

const digit = arr.length

const max = Math.pow(hex, digit)

for (let i = 0; i < max; i++) {

let str = ''

let t = i

for (let j = digit - 1; j >= 0; j--) {

let index = t

if (t) {

index = t % hex

t = ~~(t / hex)

}

str = arr[j][index] + str

}

// console.log(str)

result.push(str)

}

return result

}

console.time('begin')

console.log(arrange(arr))

console.timeEnd('begin')

用js循环如何得出该结果?

以上是 用js循环如何得出该结果? 的全部内容, 来源链接: utcz.com/p/936143.html

回到顶部