Cartesian Product On Multiple Array of Objects in Javascript - Stack Overflow
Cartesian Product On Multiple Array of Objects in Javascript - Stack Overflow
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'}]
function cartesianProductOf() {
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
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() {
a.forEach(function(a_el) {
b.forEach(function(b_el) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
});
});
return ret;
}, [{}]);
// ^^
}
If you don't want to use Object.assign or it's polyfill, the equivalent would be
var r = {};
r[p] = a_el[p];
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
R.reduce(
(Ys, X) =>
[[]],
Xs
R.map(R.mergeAll, cartesianProduct(...objs))
console.log(
cartesianProductOf(
<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
meta
chat
tour
help
blog
privacy policy
legal
contact us
cookie settings
full site
2021 Stack Exchange, Inc. user contributions under cc by-sa