Home > front end >  Merging array of arrays
Merging array of arrays

Time:12-21

The problem, I'm trying to solve is as followed

we do have an array

const array = [[1, 2, 3], ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],[" ", "-", "*", "/", "?"]];

we want to have an output like this:

const output = [[1,"A"," "],[1,"A","-"],[1,"A","*"],[1,"A","/"],[1,"A","?"],[1,"B"," "],[1,"B","-"],[1,"B","*"],[1,"B","/"],[1,"B","?"],[1,"C"," "],[1,"C","-"],[1,"C","*"],[1,"C","/"],[1,"C","?"],[1,"D"," "],[1,"D","-"],[1,"D","*"],[1,"D","/"],[1,"D","?"],[1,"E"," "],[1,"E","-"],[1,"E","*"],[1,"E","/"],[1,"E","?"],[1,"F"," "],[1,"F","-"],[1,"F","*"],[1,"F","/"],[1,"F","?"],[1,"G"," "],[1,"G","-"],[1,"G","*"],[1,"G","/"],[1,"G","?"],[1,"H"," "],[1,"H","-"],[1,"H","*"],[1,"H","/"],[1,"H","?"],[1,"I"," "],[1,"I","-"],[1,"I","*"],[1,"I","/"],[1,"I","?"],[1,"J"," "],[1,"J","-"],[1,"J","*"],[1,"J","/"],[1,"J","?"],[2,"A"," "],[2,"A","-"],[2,"A","*"],[2,"A","/"],[2,"A","?"],[2,"B"," "],[2,"B","-"],[2,"B","*"],[2,"B","/"],[2,"B","?"],[2,"C"," "],[2,"C","-"],[2,"C","*"],[2,"C","/"],[2,"C","?"],[2,"D"," "],[2,"D","-"],[2,"D","*"],[2,"D","/"],[2,"D","?"],[2,"E"," "],[2,"E","-"],[2,"E","*"],[2,"E","/"],[2,"E","?"],[2,"F"," "],[2,"F","-"],[2,"F","*"],[2,"F","/"],[2,"F","?"],[2,"G"," "],[2,"G","-"],[2,"G","*"],[2,"G","/"],[2,"G","?"],[2,"H"," "],[2,"H","-"],[2,"H","*"],[2,"H","/"],[2,"H","?"],[2,"I"," "],[2,"I","-"],[2,"I","*"],[2,"I","/"],[2,"I","?"],[2,"J"," "],[2,"J","-"],[2,"J","*"],[2,"J","/"],[2,"J","?"],[3,"A"," "],[3,"A","-"],[3,"A","*"],[3,"A","/"],[3,"A","?"],[3,"B"," "],[3,"B","-"],[3,"B","*"],[3,"B","/"],[3,"B","?"],[3,"C"," "],[3,"C","-"],[3,"C","*"],[3,"C","/"],[3,"C","?"],[3,"D"," "],[3,"D","-"],[3,"D","*"],[3,"D","/"],[3,"D","?"],[3,"E"," "],[3,"E","-"],[3,"E","*"],[3,"E","/"],[3,"E","?"],[3,"F"," "],[3,"F","-"],[3,"F","*"],[3,"F","/"],[3,"F","?"],[3,"G"," "],[3,"G","-"],[3,"G","*"],[3,"G","/"],[3,"G","?"],[3,"H"," "],[3,"H","-"],[3,"H","*"],[3,"H","/"],[3,"H","?"],[3,"I"," "],[3,"I","-"],[3,"I","*"],[3,"I","/"],[3,"I","?"],[3,"J"," "],[3,"J","-"],[3,"J","*"],[3,"J","/"],[3,"J","?"]]

We dont't know the size of the parent Array and children can have various sizes and types

CodePudding user response:

@pilchard has point out this solution: All possible combinations of a 2d array in Javascript

function combos(list, n = 0, result = [], current = []){
    if (n === list.length) result.push(current)
    else list[n].forEach(item => combos(list, n 1, result, [...current, item]))
 
    return result
}

I can confirm that it works

CodePudding user response:

You can use an inner map:

const array = [
  [1, 2, 3],
  ['A', 'B', 'C'],
  [' ', '-', '*']
];

const res = array.map((e, i) => array.map(f => f[i]))
console.log(res)

  • Related