function getCombinations(_list) {
var fn = function(active, rest, a) {
if (!active.length && !rest.length)
return;
if (!rest.length) {
a.push(active);
} else {
fn(active.concat(rest[0]), rest.slice(1), a);
fn(active, rest.slice(1), a);
}
return a;
}
return fn([], _list, []);
}
var list = [1, 2, 3, 4]
console.log(getCombinations(list));
Which returns a 2D array, filled with every combination ...
[ [ 1, 2, 3, 4 ]
, [ 1, 2, 3 ]
, [ 1, 2, 4 ]
, [ 1, 2 ]
, [ 1, 3, 4 ]
, [ 1, 3 ]
, [ 1, 4 ]
, [ 1 ]
, [ 2, 3, 4 ]
, [ 2, 3 ]
, [ 2, 4 ]
, [ 2 ]
, [ 3, 4 ]
, [ 3 ]
, [ 4 ]
]
But I want the following order
[ [ 1 ]
, [ 1, 2 ]
, [ 1, 2, 3]
, [ 1, 2, 3, 4 ]
, [ 1, 2, 4]
, [ 1, 3 ]
, [ 1, 3, 4 ]
, [ 1, 4 ]
, [ 2 ]
, ...
, [ 4 ]
]
I tried using .sort, but that sorts the combinations alphabetically
getCombinations([ 1, 2, 10 ]).sort()
// [ [ 1 ]
// , [ 1, 10 ]
// , [ 1, 2 ]
// , [ 1, 2, 10 ]
// , [ 10 ]
// , [ 2 ]
// , [ 2, 10 ]
// ]
But this is not the ordering I want.
How can I sort the array, so that the contents of the array are treated numerically, and the result is the same order as I mentioned above?
sort()method is functional programmingArray.prototype.sortmutates the original array and 2. even if it were you don't call it anywhere in the provided code. I could maybe see it qualifying because of your use of recursion. Maybe. Please read the tag description before using it on questions, I (and I assume others subscribing to the tag) don't want to get spammed with a bunch of emails not relevant to our interests.