Create cartesian product

This function generates the cartesian product of two arrays.

JavaScript:

let cartesianProduct = (arr1, arr2) => arr1.flatMap(x => arr2.map(y => [x, y]));

// Example
console.log(cartesianProduct([1, 2], ['a', 'b'])); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
console.log(cartesianProduct(['x', 'y'], [10, 20])); // [['x', 10], ['x', 20], ['y', 10], ['y', 20]]

TypeScript:

let cartesianProduct = (arr1: any[], arr2: any[]): any[] => arr1.flatMap(x => arr2.map(y => [x, y]));

// Example
console.log(cartesianProduct([1, 2], ['a', 'b'])); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
console.log(cartesianProduct(['x', 'y'], [10, 20])); // [['x', 10], ['x', 20], ['y', 10], ['y', 20]]
Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *