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:
['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"]