查找JS中2个数组的所有排列 [英] Find all permutations of 2 arrays in JS
本文介绍了查找JS中2个数组的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到2个数组的每个排列,如下所示:
I'm trying to find every permutations of 2 arrays like this:
// input
lowerWords = ['one', 'two', 'three' ]
upperWords = [ 'ONE', 'TWO', 'THREE' ]
// output
keywords = {
'one two three': true,
'ONE two three': true,
'ONE TWO three': true,
'ONE TWO THREE': true,
'ONE two THREE': true,
'one TWO three': true,
'one two THREE': true,
'one TWO THREE': true,
}
它应具有3个以上的项目,两个数组的长度始终相同。这是我的代码:
It should function with more than 3 items, both arrays will always be same length. This is my code:
const keywords = {}
const lowerWords = ['one', 'two', 'three' ]
const upperWords = [ 'ONE', 'TWO', 'THREE' ]
const wordCount = lowerWords.length
let currentWord = 0
let currentWords = [...upperWords]
while (currentWord < wordCount) {
currentWords[currentWord] = lowerWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
}
currentWord = 0
currentWords = [...lowerWords]
while (currentWord < wordCount) {
currentWords[currentWord] = upperWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
}
结果缺少一些
ONE TWO THREE: true
ONE TWO three: true
ONE two three: true
one TWO THREE: true
one two THREE: true
one two three: true
推荐答案
您可以转置数组以获取对数组,然后获取对的所有组合。
You could transpose the arrays for getting an array of pairs and then get all combinations of the pairs.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于查找JS中2个数组的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文