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

How to combine first element of one array with first element of second array and first element of first array with second element of second array

I have 2 arrays with different length and the number of items in each array is dynamic. I want to combine the first element of one array with first element of second array and first element of first array with second element of second array and so on.for example:

The first array is ['a','b','c']
The second array is ['1','2]

Finally, I need the result to look like this:

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

['a-1','a-2','b-1','b-2','c-1','c-2]

>Solution :

You can try use flatMap() to iterate over each element of array1 and use map() on array2:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['1', '2'];

const resArray = arr1.flatMap(item1 =>
  arr2.map(item2 => `${item1}-${item2}`)
);

console.log(resArray); //["a-1","a-2","b-1", "b-2","c-1","c-2"]

You can achieve the result using for loop as well:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['1', '2'];
const resArray = [];
for (let i = 0; i < arr1.length; i++) {
  for (let j = 0; j < arr2.length; j++) {
    const elem = arr1[i] + '-' + arr2[j];
    resArray.push(elem);
  }
}
console.log(resArray); //["a-1","a-2","b-1", "b-2","c-1","c-2"]
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