Rodrigo Zurek - 2 years ago 115
Javascript Question

combinations of size N from an array

I am trying to build a javascript function to get all combinations of size N from an array.
lets say I got:

``````const Xarray = ["19", "21","42","23",  "25", "28"];
const n = 4;

combinationsOfN(Xarray, n) =>

[ ["19", "21", "42", "23"],
["19", "21", "42", "25"],
["19", "21", "42", "28"],
["19", "21", "23", "25"],
["19", "21", "23", "28"],
["19", "21", "25", "28"],
…. ]
``````

Answer Source

Doing this by yourself might be rather tough, because I tried. There's already a js tool that does this for you, combinations.js

``````/**
* Copyright 2012 Akseli Palén.
* Created 2012-07-15.
* Licensed under the MIT license.
*/
function k_combinations(set, k) {
var i, j, combs, head, tailcombs;
if (k > set.length || k <= 0) {
return [];
}
if (k == set.length) {
return [set];
}
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
head = set.slice(i, i+1);
tailcombs = k_combinations(set.slice(i + 1), k - 1);
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
function combinations(set) {
var k, i, combs, k_combs;
combs = [];
for (k = 1; k <= set.length; k++) {
k_combs = k_combinations(set, k);
for (i = 0; i < k_combs.length; i++) {
combs.push(k_combs[i]);
}
}
return combs;
}

var array = ["19", "21","42","23", "25", "28"];

document.body.innerHTML += "<pre>" + JSON.stringify(k_combinations(array, 4), false, "\t") + "</pre>";``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download