How to get all combinations with different order in JS?

后端 未结 1 1447
野的像风
野的像风 2021-01-29 14:56

I\'ve got an array with six items in it.

[\'orange\', \'strawberry\', \'melon\',\'apple\',\'banana\',\'coconut\']

I was able to get many combination

相关标签:
1条回答
  • 2021-01-29 15:22

    You may have a look to this:

    a b
    
    a
    a b
    b
    b a
    

    a b c
    
    a
    a b
    a b c
    a c
    a c b
    
    b
    b a
    b a c
    b c
    b c a
    
    c
    c a
    c a b
    c b
    c b a
    

    The above shows, that you can take every item and call the function again with the array without the used item. As result, you get an array with any combination.

    function getCombinations(array) {
        var i,
            result = [];
    
        for (i = 0; i < array.length; i++) {
            result.push(
                array[i],
                ...getCombinations(array.filter((_, j) => i !== j)).map(v => array[i] + v)
            );
        }
        return result;
    }
    
    var array = ['orange', 'strawberry', 'melon', 'apple', 'banana', 'coconut'];
    
    console.log(getCombinations(array));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题