Disclaimer: I know part of this question has been asked and answered here before and yes, they have helped me get to this point so far.
Let's say I have an array that contains 2 elements and I want to find ALL possible combinations that could be made up of these elements. The order of the sets does not matter.
var myArr = ['a','b'];
Desired result
var result = [ [a], [a,b], [b], [b,a] ]
At first I thought I was looking for a power set however I do not want a null
set and I want to treat [a,b]
and [b,a]
as unique sequences NOT as equals. More info about sets, null set, and equal sets here.
So far I have written this function that will recursively loop through my array, create new arrays for each possible combinations and push them into a results array.
function getCombinations() {
var myArr = ['a','b'],
result = [];
var recurFn = function(prefix, myArr) {
for (var i = 0; i < myArr.length; i++) {
var newArray = prefix !== '' ? [prefix, myArr[i]] : [myArr[i]];
result.push(newArray);
recurFn(prefix + myArr[i], myArr.slice(i + 1));
}
}
recurFn('', myArr);
console.log(result); //[[a], [a,b], [b]]
}
Here is a fiddle with my above code.
Currently I am only returning 3 possible combinations [a], [a,b], [b]
, how can I edit my code so that I am returning [a], [a,b], [b], [b,a]
.
Thanks!