Get all possible options for a matrix in javascript

前端 未结 4 2060
后悔当初
后悔当初 2021-01-02 15:32

I have an \'item\' object in JavaScript, and the item can have settings like color, size, etc.

I need to get all possible combinations in an array.

So lets s

4条回答
  •  孤独总比滥情好
    2021-01-02 16:25

    This can be a good interview question.
    See JS Bin for running example.

    getAllPermutations(newItem);
    
    function getAllPermutations(item) {
        var permutations = [];
    
        getAllPermutations0(item, permutations, []);
        console.log(permutations);
    }
    
    function getAllPermutations0(item, permutations, array) {
        if (array && array.length === item.Settings.length) {
            permutations.push(array.slice()); // The slice clone the array
            return;
        }
    
        var index =  array.length;
        var setting = item.Settings[index];
    
        for (var i = 0; i < setting.values.length; i++) {
            if (index === 0)
                array =  [];
    
            var currValue = setting.values[i];
    
            array.push({
                SettingName: setting.name,
                value: currValue
            });
    
            getAllPermutations0(item, permutations, array);
            array.pop(); // pop the old one first
        }
    }
    

提交回复
热议问题