Find all combinations of options in a loop

后端 未结 3 2111
孤城傲影
孤城傲影 2020-12-10 05:08

I\'m looking for the best way to loop through a bunch of options to make sure that I hit all available options.

I\'ve created a feature that allows a client to build

3条回答
  •  臣服心动
    2020-12-10 05:17

    Maybe it's a late answer. But I find a different solution at geeksforgeeks. So anyone can try this.

    const hats   = ['fez','fedora'];
    const shirts = ['t-shirt','long'];
    const pants  = ['shorts','jeans'];
    const shoes  = ['sneaker','loafer'];
    
    const data = [hats, shirts, pants, shoes];
    const keys = ['hats', 'shirts', 'pants', 'shoes'];
    
    
    function combination(data, keys) {
        const { length: numberOfArrays } = data;
        
        /**
         * Initialize a variable called indices
         * with the length of data array and
         * fill with zeros.
         */
        const indices = Array(numberOfArrays).fill(0);
        const result = [];
    
        while (true) {
            let obj = {};
    
            /**
             * Get the values from the inner arrays
             * with help of `indices` and make an object
             */
            for (let i = 0; i < numberOfArrays; i++) {
                obj[keys[i]] = data[i][indices[i]];
            }
            
            // Push the object into the result array
            result.push(obj);
    
            // Get the last array
            let pick = numberOfArrays - 1;
            
            /**
             * find the rightmost array that has more 
             * elements left after the current element  
             * in that array
             */
            while (pick >= 0 && (indices[pick] + 1 >= data[pick].length)) {
                pick--;
            }
    
            /**
             * No such array is found so no more  
             * combinations left 
             */
            if (pick < 0) break;
    
            /**
             * If found move to next element in that array
             */
            indices[pick]++;
    
            /**
             * for all arrays to the right of this  
             * array current index again points to  
             * first element 
             */
            for (let i = pick + 1; i < numberOfArrays; i++) {
                indices[i] = 0;
            }
    
        }
    
        return result;
    }
    
    console.log(combination(data, keys));
    .as-console-wrapper {min-height: 100%!important; top: 0}

提交回复
热议问题