代码之家  ›  专栏  ›  技术社区  ›  Shannon Hochkins

如何从多个多维数组中创建每个可能的变体?

  •  -1
  • Shannon Hochkins  · 技术社区  · 7 年前

    我尝试过各种方法,基本上,如果我有一个红色和绿色的选项作为一组,另一组的大小,说小和大,我需要以下是正确的:

    const input = [{
        label : 'Colours',
        options: [{text : 'red'}, {text : 'green'}]
    },{
        label : 'Sizes',
        options: [{text : 'small'}, {text: 'large'}]
    }];
    

    我希望这个输出:

    red, small,
    red, large,
    green, small, 
    green, large
    

    下面是一个更复杂但类似的结构,它也应该能够从相同的代码生成:

    [{"label":"Fitting Options","options":[{"text":"No Thanks","value":"no-thanks","price":0},{"text":"Yes Please (+$110.00 )","value":"yes-please","price":"110.00"}]},{"label":"Memory Card Size","options":[{"text":"128GB (+$180.00 )","value":"128gb","price":"180.00"},{"text":"16GB","value":"16gb","price":0},{"text":"32GB (+$30.00 )","value":"32gb","price":"30.00"},{"text":"64GB (+$80.00 )","value":"64gb","price":"80.00"}]}]
    

    Get all variants from a multidimensional array in javascript

    1 回复  |  直到 7 年前
        1
  •  0
  •   Maheer Ali    7 年前

    我只是想找出一个这个。是我的有点难以解释。这只是一个组合算法。

    2 i index of input . j index of options of current obj . 这些值直到 a b 到达终点。

    function findComb(arr,result,i,j,a,b){	result.push([arr[i].options[j].text,arr[a].options[b].text]);
    	if(arr[a].options[b + 1]) b++;
    	else if(arr[a + 1]) a++;
    	else{
    		if(arr[i].options[j + 1]){
    			j++
    			a = i + 1
    			b = 0
    		}
    		else if(arr[i + 2]){
    			i++;
    			j = 0;
    			a = i + 1;
                b = 0			
    		}
    		else return result;
    		
    	}
    	return findComb(arr,result,i,j,a,b)
    }
    
    
    const input1 = [{
        label : 'Colours',
        options: [{text : 'red'}, {text : 'green'}]
    },{
        label : 'Sizes',
        options: [{text : 'small'}, {text: 'large'}]
    }];
    const input2 = [{
        label : 'Colours',
        options: [{text : 'red'}, {text : 'green'},{text:"blue"}]
    },{
        label : 'Sizes',
        options: [{text : 'small'}, {text: 'large'},{text: 'medium'}]
    }];
    
    console.log(findComb(input1,[],0,0,1,0))
    console.log(findComb(input2,[],0,0,1,0))