Combine each element of an array with the ones after it

I am trying to combine items in an array, with every item below it. It should make a set of the current character and each character below it, and iteratively walk down the array. For example, if I have an array like this:

var myArray = ['A','B','C','D']

I would like an output like this:

AB AC AD BC BD CD

The code I have is getting me close, but I am having a hard time figuring out the rest. Here is what I have so far:

var myArray = ['A', 'B', 'C', 'D']
var sql_parts = []
var string = "";
for (var i = 0; i < myArray.length; i++) {
  recurse_function(string, i)
}
console.log(sql_parts)

function recurse_function(string_val, count) {
  if ((myArray.length - count) == 0) {
    return string_val;
  } else {
    string_val += myArray[count]
    sql_parts.push(string_val)
    recurse_function(string_val, count + 1)
  }
}

But this produces:

[“A”, “AB”, “ABC”, “ABCD”, “B”, “BC”, “BCD”, “C”, “CD”, “D”]

Answer

Here is one solution:

  • Define the recursive function to take the array and an empty list initially to store the combinations
  • The base condition is when the array is empty or has one element
  • Otherwise, Remove the first element “start”
  • Iterate over the array to store its combinations with its following elements
  • Recur again with array and combinations updated

function recurse_function(array, combinations = []) {
  if(array.length <= 1) return combinations;
  const start = array.shift();
  for(let i = 0; i < array.length; i++) combinations.push(`${start}${array[i]}`);
  return recurse_function(array, combinations);
}

console.log( recurse_function(['A','B','C','D']) );