iterate array of arrays and concat in javascript

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));


You can do with reduce and flat

arr1= [["a", "b"], ["c", "d"]] ;
arr2=[["a", "b"], ["c", "d"], ["e", "f"]];
arr3=[["a", "b"], ["c", "d"], ["e", "f"],, ["g", "h"]];
function calculate(arr) {
  return arr.reduce(function(a, b) {
     return a.map( function(x) { return b.map(function(y) { return x.concat([y])})}).flat().flat()}, [[]]);
}
console.log(calculate(arr1)); 

console.log(calculate(arr2));

console.log(calculate(arr3));


You can do this with one for loop and recursion where you use one param to keep index of the current sub-array that you use for loop on, and increment that value on each level. This is Cartesian product

const data = [["a", "b"], ["c", "d"], ["e", "f"]]

function cartesian(data, prev = '', n = 0) {
  const result = []

  if (n >= data.length) {
    result.push(prev);
    return result;
  }

  for (let i = 0; i < data[i].length; i++) {
    let val = prev + data[n][i];
    result.push(...cartesian(data, val, n + 1))
  }

  return result;
}

console.log(cartesian(data));

Another approach with reduce method that will create recursive call only if current n value is less then data.length - 1.

const data = [["a", "b"], ["c", "d"], ["e", "f"]]

function cartesian(data, prev = '', n = 0) {
  return data[n].reduce((r, e) => {
    let value = prev + e;

    if (n < data.length - 1) {
      r.push(...cartesian(data, value, n + 1))
    }

    if (value.length == data.length) {
      r.push(value)
    }

    return r;
  }, [])
}

const result = cartesian(data);
console.log(result);