最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

iterate array of arrays and concat in javascript - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited May 20, 2020 at 17:40 Bucket 7,5319 gold badges37 silver badges48 bronze badges asked May 20, 2020 at 16:52 sunsun 1,9724 gold badges20 silver badges34 bronze badges 3
  • can we achieve without using for loop – sun Commented May 20, 2020 at 17:00
  • If you had zip like this, it would be trivial: zip(...inputArray).map(x => x.join()). – 9000 Commented May 20, 2020 at 17:13
  • @9000 zip logic isn't suitable here, because it zips pairs from each array once, it doesn't generate all binations, which is what the question about. – vitaly-t Commented Dec 19, 2021 at 16:30
Add a ment  | 

4 Answers 4

Reset to default 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));

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

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

发布评论

评论列表(0)

  1. 暂无评论