You are on page 1of 4

Stack Overflow Sign up Log in

Questions Jobs Tags Users Badges Ask

1 Cartesian product on multiple array of objects in javascript


javascript
arrays
cartesian-product

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.

Share
Improve this question
Follow
Ghazanfar Khan asked
3,375 ● 6 ● 37 ● 80 Nov 28 '16 at 21:14

Lahar Shah
edited
5,920 ● 4 ● 25 ● 39 Nov 28 '16 at 21:40

is there a reason you need to use reduce?


– Luke Kot-Zaniewski
Nov 28 '16 at 22:12

I believe the true Cartesian Product here is actually {{col1:'A'},{col2:'B'}},{{col1:'A'},{col3:'C'}} . However,


that is not a valid javascript construct as a javascript object must be a name-value pair.
– nurdyguy
Nov 28 '16 at 22:29

Add a comment

2 Answers order by
votes

Instead of using an array to push to, you want to merge the objects:
2

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

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);

Share
Improve this answer
Follow

Bergi
answered
548k ● 122 ● 864 ● 1222 Nov 28 '16 at 22:54

-2
Here's a solution using 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>

Share
Improve this answer
Follow

Chris Vouga
answered
484 ● 4 ● 4 Jun 6 '19 at 4:45

edited
Jun 6 '19 at 6:01

Your Answer

Body


Add picture

Log in

OR

Name

Email
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Post Your Answer

meta
chat
tour
help
blog
privacy policy
legal
contact us
cookie settings
full site
2021 Stack Exchange, Inc. user contributions under cc by-sa

You might also like