8

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.

Bucket
  • 7,415
  • 9
  • 35
  • 45
sun
  • 1,832
  • 4
  • 19
  • 31
  • can we achieve without using for loop – sun May 20 '20 at 17:00
  • If you had `zip` [like this](https://stackoverflow.com/a/10284006/223424), it would be trivial: `zip(...inputArray).map(x => x.join())`. – 9000 May 20 '20 at 17:13
  • @9000 `zip` logic isn't suitable here, because it zips pairs from each array once, it doesn't generate all combinations, which is what the question about. – vitaly-t Dec 19 '21 at 16:30

4 Answers4

3

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));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
3

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));
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
2

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);
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

Here is iterative approach. Iterate over array of arrays, on each array, update the output items.

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

let output = [""];
data.forEach(arr => {
  const temp = [];
  arr.forEach(item => output.forEach(curr => temp.push(`${curr}${item}`)));
  output = [...temp];
});

console.log(output);
Siva K V
  • 10,561
  • 2
  • 16
  • 29