Javascript Permutations and Combinations of Array Values

By | January 25, 2017

In this tutorial, The JavaScript functions to calculate combinations of elements in Array. This JavaScript algorithm will find all combinations of JavaScript array values. This algorithm is one of the most efficient way to get permutations and combinations of Array values.

Find the permutations and combinations JavaScript algorithm

function getPermutation(array, prefix) {
  prefix = prefix || '';
  if (!array.length) {
  	return prefix;
  }

  var result = array[0].reduce(function (result, value) {
  	return result.concat(getPermutation(array.slice(1), prefix + value));
  }, []);
  return result;
}

Input

['a','b','c'], ['12','45'],['67','89']

OutPut

a1267
a1289
a4567
a4589
b1267
b1289
b4567
b4589
c1267
c1289
c4567
c4589

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

Demo

Author: CV

I am a Front-end Developer, graduate of Information Technology, and founder of w3tweaks.com. I have 12+ years commercial experience providing front-end development, producing high quality responsive websites and exceptional user experience.