How to Create Unique Combinations with Cartesian Product

May 28, 2022 | O. Wolfson
javascript

The Cartesian Product is the set of unique combinations derived from a pair of sets. More on Wikipedia.

This article presents code that calculates the cartesian product in JavaScript for combinations of layered images.

We can calculate cartesian product in JavaScript as follows.

const cartesian = (...a) =>
 a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e].flat())));
let output = cartesian(...arrayOfSets);

This code works by comparing pairs from an array of sets using the reduce and map functions, producing unique combinations.

If you are interested to understand the cartesian product more deeply, watch a video that explains the cartesian product with visualizations.

Test the concept with the app below. This app will accept image files as ‘layers’ and output all unique combinations of those layers. To use the app start by creating layers, then add images. Press the ‘Combine Layers’ button to calculate the unique combinations.

Find the HTML for this app, which includes code to calculate the cartesian product in JavaScript here.