Generate all combinations from arrays of options. Perfect for e-commerce variant generation, configuration matrices, and test case generation. Zero dependencies.
Works in Node.js, Cloudflare Workers, Deno, Bun, and browsers.
npm install @arraypress/cartesian-productGenerate the cartesian product of multiple arrays.
import { cartesian } from '@arraypress/cartesian-product';
cartesian(['S', 'M', 'L'], ['Red', 'Blue'])
// [['S','Red'], ['S','Blue'], ['M','Red'], ['M','Blue'], ['L','Red'], ['L','Blue']]
cartesian(['S', 'M'], ['Red', 'Blue'], ['Cotton', 'Silk'])
// 8 combinations (2 x 2 x 2)Generate combinations as objects with named keys. Ideal for variant generation.
import { cartesianObject } from '@arraypress/cartesian-product';
cartesianObject({ Size: ['S', 'M', 'L'], Color: ['Red', 'Blue'] })
// [
// { Size: 'S', Color: 'Red' },
// { Size: 'S', Color: 'Blue' },
// { Size: 'M', Color: 'Red' },
// { Size: 'M', Color: 'Blue' },
// { Size: 'L', Color: 'Red' },
// { Size: 'L', Color: 'Blue' },
// ]Count total combinations without generating them. Useful for validation before generating large sets.
import { cartesianCount } from '@arraypress/cartesian-product';
cartesianCount(['S', 'M', 'L'], ['Red', 'Blue']) // 6
cartesianCount(['S', 'M'], ['Red', 'Blue'], ['Cotton']) // 4E-commerce variants:
const options = {
Size: ['S', 'M', 'L', 'XL'],
Color: ['Red', 'Blue', 'Black'],
Material: ['Cotton', 'Polyester'],
};
// Check count first
const count = cartesianCount(...Object.values(options));
console.log(`${count} variants will be generated`); // 24
// Generate variant objects
const variants = cartesianObject(options);
// [{ Size: 'S', Color: 'Red', Material: 'Cotton' }, ...]Test matrices:
const browsers = ['Chrome', 'Firefox', 'Safari'];
const devices = ['Desktop', 'Mobile', 'Tablet'];
const testCases = cartesian(browsers, devices);
// 9 test case combinationsMIT