How to get all combinations of some arrays in JavaScript?


You can use your own function to get all combinations.

Example

Following is the code −

function combination(values) {
   function * combinationRepeat(size, v) {
      if (size)
         for (var chr of values)
      yield * combinationRepeat(size - 1, v + chr);
      else yield v;
   }
   return [...combinationRepeat(values.length, "")];
}
var output = combination([4,5]);
console.log(output);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo306.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo306.js
[ '44', '45', '54', '55' ]

Updated on: 24-Oct-2020

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements