javascript 中具有嵌套数组和非数值的笛卡尔积

Cartesian Product with nested arrays and non numerical values in javascript

我有以下代码:

     filters = [
          { 
            "see":false,
            "make":true,
            "means":true,
          },
          {
            "less":false,
            "up3":false,
            "up6":false,
            "all":true,
            "more":false,
            "var":false
          },
          {
            "one":false,
            "small":true,
            "medium":false,
            "large":false
          }
        ];

    function cartesianProductOf() {
        return _.reduce(arguments, function(a, b) {
            return _.flatten(_.map(a, function(x) {
                return _.map(b, function(y) {
                    return x.concat([y]);
                });
            }), true);
        }, [ [] ]);
    }

    function cleaning(collection){
        var r = [];
        _.each(collection,function(element,index){
            r[index] = [];

            if(_.isObject(element)){ 
                r[index] = _.map(element,function(val,key){ 
                    if(val) return key; 
                }); 
            }
            r[index] = _.compact(r[index]);

        });
        return r;
    }


    // cleaning is producing following array 
    // [["make","means"],["all"],["small"]] 

    clean = cleaning(filters);
    prod = cartesianProductOf(clean);

    $('#result').append(JSON.stringify(  prod ));

我期待这样的结果:[["make","all","small"], ["means","all","small"]]

但我得到的是 [[["make","means"]],[["all"]],[["small"]]]

笛卡尔积算法来自这里:Cartesian product of multiple arrays in JavaScript

这是我的 fiddle:https://jsfiddle.net/NFSfs/17/ 任何想法将不胜感激。

简而言之:

只需更改为

prod = cartesianProductOf.apply(null, clean);

哪里写错了:

答案很简单,你遇到了典型的动态语言类型问题,cartesianProductOf 是 "arguments" 中的等待数组,这意味着所有数组都应该在用逗号分隔的括号中传递:

cartesianProductOf(["make","means"],["all"],["small"])

但您只传递了一个参数,即列表列表

cartesianProductOf([["make","means"],["all"],["small"]])

并且函数完全按照预期执行,return初始数组,因为一个数组的笛卡尔积是那个数组