JavaScript,从几个数组中获取所有独特的组合

时间:2018-06-01 12:57:50

标签: javascript generator combinations

我正在寻找一种从多个阵列生成所有可能组合的方法。谈到1,我能够找到解决方案,但是当涉及到更多时,它就会出现问题。为了更容易理解我的问题,我们假设我们有两个数组:.unpinned{ height: calc(100vh - 430px); } .pinned{ height: calc(100vh - 447px); } .pinned{ -ms-overflow-style: none; overflow: auto; width: 560px; } .unpinned{ overflow: scroll; flex: 1; } /deep/ .pinned::-webkit-scrollbar { width: 0; } ['small','big'],我想要获得的结果是:

小绿球小红球大绿球大红球绿球红球小球大球绿色小球红色大球等。

对我来说最大的困难在于弄清楚如何制作它,以便每个阵列都不会有任何重复,例如:小型大球绿色红球

2 个答案:

答案 0 :(得分:1)

这是我的解决方案



let sizes = ['small', 'medium sized', 'big']
let colors = ['green', 'red', 'blue']
let objects = ['ball', 'square']

const flatten = list => list.reduce(
   (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);

function uniqeCombine(...data) {
  
  const flat = flatten(data);
  return flat.reduce( (acc, v, i) =>
    acc.concat(flat.slice(i+1).map( w => v + ' ' + w )),
  []);
}


console.log(uniqeCombine(sizes, colors, objects))




答案 1 :(得分:0)

使用嵌套for循环。使用for of,您可以轻松遍历数组中的每个对象:



let sizes = ['small', 'medium sized', 'big']
let colors = ['green', 'red', 'blue']
let objects = ['ball', 'square']

for (size of sizes) {
  for (color of colors) {
    for (object of objects) {
      console.log(size, color, object)
    }
  }
}




获取green big ballbig green ball



const sizes = ['small', 'big']
const colors = ['green', 'red']

for (let size of sizes) {
  for (let color of colors) {
    console.log(size, color, 'ball')
  }
}
for (let color of colors) {
  for (let size of sizes) {
    console.log(color, size, 'ball')
  }
}