say I have an array [["a", "b"], ["c", "d"]]
how can I iterate or reduce or map or join this array and get ["ac", "ad", "bc", "bd"]
and if array is like [["a", "b"], ["c", "d"], ["e", "f"]]
I should get like ["ace", "acf", "ade", "adf", "bce", "bcf", "bde", "bdf"]
how can we achieve this using array iteration or methods?
I tried by using reduce:
const output = [];
const sol = array.reduce((cum, ind) => {
for (let i = 0; i <= cum.length; i++ ) {
for (let j = 0; j <= ind.length; j++) {
output.push(`${cum[i]} + ${ind[j]}`);
}
}
});
console.log(output);
but I didn't get the exact output.
I'd use a recursive approach: iterate over the first array, then do a recursive call to retrieve the strings for the second and later arrays. Do this recursively until you reach the end of the arrays. Then, on the way back, you can push the recursive result concatenated with each element of the current array:
const recurse = (arr) => {
const subarr = arr.shift();
if (!subarr) return;
const result = [];
for (const laterStr of recurse(arr) || ['']) {
for (const char of subarr) {
result.push(char + laterStr);
}
}
return result;
}
const arr = [["a", "b"], ["c", "d"], ["e", "f"]];
console.log(recurse(arr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With