一尘不染

Javascript-生成单个数组中的所有元素组合(成对)

algorithm

我已经看到了几个有关如何生成数组中元素的所有可能组合的类似问题。但是我很难弄清楚如何编写只输出组合 的算法。任何建议将不胜感激!

从以下数组(具有N个元素)开始:

var array = ["apple", "banana", "lemon", "mango"];

并得到以下结果:

var result = [
   "apple banana"
   "apple lemon"
   "apple mango"
   "banana lemon"
   "banana mango"
   "lemon mango"
];

我正在尝试以下方法,但这会导致所有可能的组合,而不是仅组合对。

var letters = splSentences;
var combi = [];
var temp= "";
var letLen = Math.pow(2, letters.length);

for (var i = 0; i < letLen ; i++){
    temp= "";
    for (var j=0;j<letters.length;j++) {
        if ((i & Math.pow(2,j))){ 
            temp += letters[j]+ " "
        }
    }
    if (temp !== "") {
        combi.push(temp);
    }
}

阅读 576

收藏
2020-07-28

共1个答案

一尘不染

一种简单的方法是对数组执行double for循环,在该数组中跳过i第二个循环中的第一个元素。

let array = ["apple", "banana", "lemon", "mango"];

let results = [];



// Since you only want pairs, there's no reason

// to iterate over the last element directly

for (let i = 0; i < array.length - 1; i++) {

  // This is where you'll capture that last value

  for (let j = i + 1; j < array.length; j++) {

    results.push(`${array[i]} ${array[j]}`);

  }

}



console.log(results);

用ES5重写:

var array = ["apple", "banana", "lemon", "mango"];

var results = [];



// Since you only want pairs, there's no reason

// to iterate over the last element directly

for (var i = 0; i < array.length - 1; i++) {

  // This is where you'll capture that last value

  for (var j = i + 1; j < array.length; j++) {

    results.push(array[i] + ' ' + array[j]);

  }

}



console.log(results);
2020-07-28