Javascript - Generating all combinations of elements in a single array (in pairs)

后端 未结 9 644
天命终不由人
天命终不由人 2020-11-28 11:14

I\'ve seen several similar questions about how to generate all possible combinations of elements in an array. But I\'m having a very hard time figuring out how to write an a

9条回答
  •  悲哀的现实
    2020-11-28 11:39

    A simple way would be to do a double for loop over the array where you skip the first i elements in the second loop.

    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);

    Rewritten with 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);

提交回复
热议问题