Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get all combinations of some arrays in JavaScript?
Getting all combinations of arrays in JavaScript can be accomplished using recursive generator functions or iterative approaches. This is useful for creating permutations, product combinations, and other algorithmic solutions.
Using Generator Function (Cartesian Product)
A generator function can efficiently create all combinations by recursively building each possibility:
function getAllCombinations(values) {
function* generateCombinations(size, current) {
if (size) {
for (var element of values) {
yield* generateCombinations(size - 1, current + element);
}
} else {
yield current;
}
}
return [...generateCombinations(values.length, "")];
}
var result = getAllCombinations([4, 5]);
console.log("Combinations:", result);
Combinations: [ '44', '45', '54', '55' ]
Multiple Arrays Combination
For combining elements from different arrays, use this approach:
function combineArrays(...arrays) {
return arrays.reduce((acc, curr) => {
const result = [];
acc.forEach(a => {
curr.forEach(c => {
result.push([...a, c]);
});
});
return result;
}, [[]]);
}
var colors = ['red', 'blue'];
var sizes = ['small', 'large'];
var combinations = combineArrays(colors, sizes);
console.log("Array combinations:");
combinations.forEach(combo => console.log(combo));
Array combinations: [ 'red', 'small' ] [ 'red', 'large' ] [ 'blue', 'small' ] [ 'blue', 'large' ]
Using Nested Loops for Simple Cases
For two arrays, nested loops provide a straightforward solution:
function simpleCombination(arr1, arr2) {
const combinations = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
combinations.push([arr1[i], arr2[j]]);
}
}
return combinations;
}
var numbers = [1, 2];
var letters = ['A', 'B'];
var pairs = simpleCombination(numbers, letters);
console.log("Simple combinations:");
pairs.forEach(pair => console.log(pair));
Simple combinations: [ 1, 'A' ] [ 1, 'B' ] [ 2, 'A' ] [ 2, 'B' ]
Comparison
| Method | Best For | Performance | Complexity |
|---|---|---|---|
| Generator Function | Self-combinations | Memory efficient | Medium |
| Array Reduce | Multiple different arrays | Good | High |
| Nested Loops | Two arrays only | Fast | Low |
Conclusion
Choose generator functions for self-combinations and memory efficiency, array reduce for multiple different arrays, or nested loops for simple two-array combinations. Each method serves different use cases effectively.
Advertisements
