Home > Software design >  Javascript - All Possible Combinations From Single Array Every Order
Javascript - All Possible Combinations From Single Array Every Order

Time:04-15

enter image description here

CodePudding user response:

At first create function to find all combinations of array:

function combinations(array) {
  return new Array(1 << array.length).fill().map(
    (e1, i) => array.filter((e2, j) => i & 1 << j));
}

Then you have to create function to generate all permutations of given array (for example this using Heap's method:

function permute(permutation) {
  var length = permutation.length,
      result = [permutation.slice()],
      c = new Array(length).fill(0),
      i = 1, k, p;

  while (i < length) {
    if (c[i] < i) {
      k = i % 2 && c[i];
      p = permutation[i];
      permutation[i] = permutation[k];
      permutation[k] = p;
        c[i];
      i = 1;
      result.push(permutation.slice());
    } else {
      c[i] = 0;
        i;
    }
  }
  return result;
}

After that you can combine that to final function:

function calculateAllCombinations(myArray) {
    var allValues = combinations(myArray)

    var response = allValues

    for(let v of allValues) {
        response = response.concat(permute(v))
    }

    //Return removed duplicates
    return Array.from(new Set(response.map(JSON.stringify)), JSON.parse)

}

At the end you can call it like this:

var myArray = ["apple", "banana", "lemon", "mango"]

var allValues = calculateAllCombinations(myArray)
  • Related