I currently have an Javascript array of unknown length, containing arrays (of unknown length) of strings. I'm looking for a way to find every possible combination, using one string from every second level array. Note: order of the strings do not matter. That is, for:
[
[
'a',
'b'
],
[
'c',
'd'
]
]
I would like to return:
[
'ac',
'ad',
'bc',
'bd'
]
or, given:
[
[
'a',
'b'
],
[
'1'
],
[
'i',
'j',
'k',
]
]
I would like to return:
[
'a1i',
'a1j',
'a1k',
'b1i',
'b1j',
'b1k',
]
I feel like the answer lies in a recursive function, however I cannot seem to get it work (the variable scoping keeps getting confusing and it just falls flat).
Instead, I've tried another way of creating a results array, looping through each subarray and placing each string in the results in such a way that each possible combination is created:
function getArrayStrings(allTerms){
// get total number of possible combinations
var numberOfElements = 1;
$.each(allTerms, function(index, element){
numberOfElements *= element.length;
});
// create array of results
var result = [];
for(i = 0; i < numberOfElements; i ++){
result[i] = '';
}
// instantiate variables that will be used in loop
var elementToUse = 0;
var currentLength = 1;
var prevLength = 1;
// for each array, loop through values and add them to the relevant result element
$.each(allTerms, function(index, array){
// find length of current array
currentLength = array.length;
elementToUse = 0;
// for each of the elements in the results array
for(i = 0; i < numberOfElements; i ++){
// change the element to use if you've looped through the previous length (but not if it's first result
if(i !== 0 && i % prevLength === 0){
elementToUse ++;
}
// return to using the first element if you've reached the last element in the sub array
if(elementToUse % currentLength === 0){
elementToUse = 0;
}
result[i] += '.' + array[elementToUse];
}
prevLength = array.length * prevLength;
});
console.log(result.join(''));
return result.join('');
}
This does work, however I wondered whether anyone knew of a simpler function; I feel like this is something that would have some Javascript (or jQuery) function in there already, but I can't find it.
Has anyone come across a challenge like this before? And, if so, how did you approach it?