Zulu Zulu - 2 months ago 14
Javascript Question

Creating an array without hard-coding

I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:

var someStr = ["a","b","c","d"];

//I want to produce this outcome

a
ab
abc
abcd
b
bc
bcd
c
cd
d


I know I can get the # of possibilities for "a" only by this way:

var numCombinations = 0;
var comboString = '';
var outcome = [];

for(var i = 0; i < someStr.length; i++){

comboString += someStr[i];

outcome[i] = comboString;

numCombinations += i; //# of combinations from above

}


But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?

Answer Source

Hope this help.

function getComboStringListFromIdx(arr, idx){
    var result = [];
    var comboString = '';
    for(var i=idx; i<arr.length; i++){
        comboString += arr[i];
        result.push(comboString);
    }
    return result;
}

var someStr = ['a','b','c','d'];

var outCome = [];
for(var i = 0; i<someStr.length; i++){
    outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}