小编典典

在JS中找到2个数组的所有排列

algorithm

我试图找到这样的2个数组的每个排列:

// 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个以上的项,两个数组的长度始终相同。这是我的代码:

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

阅读 273

收藏
2020-07-28

共1个答案

小编典典

您可以转置数组以获取对数组,然后获取对的所有组合。

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; }
2020-07-28