Javascript - Generating all combinations of elements in a single array (in pairs)

后端 未结 9 645
天命终不由人
天命终不由人 2020-11-28 11:14

I\'ve seen several similar questions about how to generate all possible combinations of elements in an array. But I\'m having a very hard time figuring out how to write an a

9条回答
  •  时光说笑
    2020-11-28 11:33

    In my case, I wanted to get the combinations as follows, based on the size range of the array:

    function getCombinations(valuesArray: String[])
    {
    
    var combi = [];
    var temp = [];
    var slent = Math.pow(2, valuesArray.length);
    
    for (var i = 0; i < slent; i++)
    {
        temp = [];
        for (var j = 0; j < valuesArray.length; j++)
        {
            if ((i & Math.pow(2, j)))
            {
                temp.push(valuesArray[j]);
            }
        }
        if (temp.length > 0)
        {
            combi.push(temp);
        }
    }
    
    combi.sort((a, b) => a.length - b.length);
    console.log(combi.join("\n"));
    return combi;
    }
    

    Example:

    // variable "results" stores an array with arrays string type
    let results = getCombinations(['apple', 'banana', 'lemon', ',mango']);
    

    Output in console:

    The function is based on the logic of the following documentation, more information in the following reference: https://www.w3resource.com/javascript-exercises/javascript-function-exercise-3.php

提交回复
热议问题