Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to dynamically combine all provided arrays using JavaScript?
Suppose we have two arrays of literals like these −
const arr1= ['a', 'b', 'c']; const arr2= ['d', 'e', 'f'];
We are required to write a JavaScript function that takes in two such arrays and build all possible combinations from the arrays.
So, for these two arrays, the output should look like −
const output = [ad, ae, af, bd, be, bf, cd, ce, cf];
Example
The code for this will be −
const arr1= ['a', 'b', 'c'];
const arr2= ['d', 'e', 'f'];
const combineArrays = (...arr) => {
const res = [];
const combinePart = (part, index) => {
arr[index].forEach(el => {
const p = part.concat(el);
if(p.length === arr.length){
res.push(p.join(''));
return;
};
combinePart(p, index + 1);
});
};
combinePart([], 0);
return res;
}
console.log(combineArrays(arr1, arr2));
Output
And the output in the console will be −
[ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf' ]
Advertisements