Home > Web Front-end > JS Tutorial > How Can I Efficiently Generate Cartesian Products of Arrays in JavaScript?

How Can I Efficiently Generate Cartesian Products of Arrays in JavaScript?

Patricia Arquette
Release: 2024-12-16 07:13:10
Original
670 people have browsed it

How Can I Efficiently Generate Cartesian Products of Arrays in JavaScript?

Generating Cartesian Products of Arrays in JavaScript

Calculating the Cartesian product of multiple arrays is a common task in programming. It involves combining elements from each array to create new arrays containing all possible combinations. To achieve this in JavaScript, we can employ various approaches.

One simplistic but outdated approach requires iterating over each array and manually generating all possible combinations. However, this method becomes inefficient for large datasets. Instead, we can leverage advanced techniques in ES6 and ES2019 to significantly simplify the process.

Optimized 2020 Solution

With the introduction of flatMap in ES2019, we can reduce the Cartesian product calculation to a single concise line of code:

const cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
Copy after login

Example Usage

To illustrate, let's consider the example provided in your question:

const output = cartesian([1, 2], [10, 20], [100, 200, 300]);
Copy after login

This command generates the following Cartesian product:

[
  [ 1, 10, 100 ],
  [ 1, 10, 200 ],
  [ 1, 10, 300 ],
  [ 1, 20, 100 ],
  [ 1, 20, 200 ],
  [ 1, 20, 300 ],
  [ 2, 10, 100 ],
  [ 2, 10, 200 ],
  [ 2, 10, 300 ],
  [ 2, 20, 100 ],
  [ 2, 20, 200 ],
  [ 2, 20, 300 ]
]
Copy after login

Conclusion

By embracing modern JavaScript features, we can tackle complex tasks like Cartesian product calculations with remarkable ease. Whether it's for algorithm development or data manipulation, these techniques empower developers to code more efficiently and elegantly.

The above is the detailed content of How Can I Efficiently Generate Cartesian Products of Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template