Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading