Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate array of arrays and concat in javascript

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.

like image 844
sun Avatar asked May 20 '20 16:05

sun


1 Answers

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));
like image 182
CertainPerformance Avatar answered Nov 14 '22 07:11

CertainPerformance