JSFiddle - React, Tailwind, and code Playground
by robaldred
HTML
<div id="combinations">test</div>
JavaScript
var arr = ['A','B','C'];
var combinations = function(arr,r) {
var pool = arr;
var n = pool.length;
if(r > n) {
return;
}
var indices = [0,1];
var res = [];
var tmp = [];
for(var i = 0;i < indices.length;i++) {
tmp.push(pool[indices[i]]);
}
res.push(tmp);
(function() {
while(true) {
var reversed_ind = [1,0];
var i;
for(i = 0;i<reversed_ind.length;i++) {
if(indices[reversed_ind[i]] != (reversed_ind[i] + n - r))
break;
if(i==indices.length-1)
return;
}
indices[reversed_ind[i]] += 1;
var tmp = [0,1].slice(reversed_ind[i]+1,r);
for(var j = 0;j<tmp.length;j++) {
indices[tmp[j]] = indices[tmp[j]-1] + 1;
}
var tmp = [];
for(var i = 0; i < indices.length;i++) {
tmp.push(pool[indices[i]]);
}
res.push(tmp);
}
})();
return res;
};
var combs = combinations(arr,2);
$('#combinations').text(combs.length);
console.log(combs);