Search code examples
javascriptarraysconcatenation

Concatenate all combinations of elements in two separate arrays


How would you take two arrays and concatenate the elements and return them in a new array? For instance here are two arrays:

const whoArr = ["my", "your"];    
const credentialArr = ["name", "age", "gender"].   

I would like to return a new array containing the elements:

["my name", "my age", "my gender", "your name", "your age", "your gender"]

.join and .concat don't quite work.


Solution

  • You can use nested loops to loop over array 1, and for each iteration, you loop over array 2.

    Here I use forEach() but you can use a normal for loop or a for of loop too:

    const whoArr = ["my", "your"];
    const credentialArr = ["name", "age", "gender"];
    
    const output = [];
    whoArr.forEach(who => {
      credentialArr.forEach(cred => {
        output.push(who + ' ' + cred)
      })
    })
    
    console.log(output)

    Here's the same approach but using for of loops and template literals to make the string:

    const whoArr = ["my", "your"];
    const credentialArr = ["name", "age", "gender"];
    
    const output = [];
    for (let who of whoArr) {
      for (let cred of credentialArr) {
        output.push(`${who} ${cred}`);
      }
    }
    
    console.log(output)