简体   繁体   English

javascript中多个对象数组上的笛卡尔积

[英]Cartesian product on multiple array of objects in javascript

I have been working on cartesian product for single elements and array of objects. 我一直在研究单个元素和对象数组的笛卡尔积。 For single array elements I have understood the solution but for array of objects I struggle to achieve. 对于单数组元素,我已经理解了解决方案,但是对于对象数组,我却难以实现。 For example input 例如输入

cartesianProductOf([{col1:'A'}], [{col2:'B'},{col3:'C'}]) 

Output : 输出:

[{col1:'A',col2:'B'},{col1:'A',col3:'C'}]

Here is the function which I was working on 这是我正在研究的功能

function cartesianProductOf() {
     return Array.prototype.reduce.call(arguments, function(a, b) {

         var ret = [];
         debugger;

         a.forEach(function(a) {
                 b.forEach(function(b) {
                 var r = a.concat([b])
                 ret.push(r);
             });
         });

         return ret;

    }, [[]]);
}

This function returning this result 这个函数返回这个结果

[{col1:'A'},{col2:'B'}],[{col1:'A'},{col3:'C'}]

Need guidance. 需要指导。

Instead of using an array to push to, you want to merge the objects: 您想要合并对象,而不是使用数组进行推送:

function cartesianProductOf() {
     return Array.prototype.reduce.call(arguments, function(a, b) {
         var ret = [];
         a.forEach(function(a_el) {
             b.forEach(function(b_el) {
                 ret.push(Object.assign({}, a_el, b_el));
//                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             });
         });
         return ret;
    }, [{}]);
//      ^^
}

If you don't want to use Object.assign or it's polyfill, the equivalent would be 如果您不想使用Object.assign或它的polyfill,则等效为

                 var r = {};
                 for (var p in a_el)
                     r[p] = a_el[p];
                 for (var p in b_el)
                     r[p] = b_el[p];
                 ret.push(r);

Here's a solution using Ramda.js 这是使用Ramda.js的解决方案

 const cartesianProduct = (...Xs) => R.reduce( (Ys, X) => R.map(R.apply(R.append), R.xprod(X, Ys)), [[]], Xs ) const cartesianProductOf = (...objs) => R.map(R.mergeAll, cartesianProduct(...objs)) console.log( cartesianProductOf( [{col1: 'A'}],[{col2: 'B'}, {col3: 'C'}], ) ) 
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM