简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM