Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Get All Combinations of 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: 2020-10-24T12:22:27+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements