I have following code:
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 ));
I'm expecting result along the lines: [["make","all","small"], ["means","all","small"]]
but I'm getting [[["make","means"]],[["all"]],[["small"]]]
instead.
The Cartesian Product Algorithm is from here: Cartesian product of multiple arrays in JavaScript
here is my fiddle: https://jsfiddle.net/NFSfs/17/ Any Idea would be appreciated.
In short:
just change to
prod = cartesianProductOf.apply(null, clean);
Where was mistake:
The answer is very simple, you stuck with classic dynamic language problem with types, cartesianProductOf is waiting array in "arguments" that mean all arrays should be passed in parenthesis delimited by comma:
cartesianProductOf(["make","means"],["all"],["small"])
but you are passing only one argument that is list of lists
cartesianProductOf([["make","means"],["all"],["small"]])
and function does exactly it should, return the initial array because of cartesian product of one array is that array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.