I have two array:
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];
How can I get the following result?
aaa f1, aaa f2, aaa f3, bbb f1, bbb f2, bbb f3
I have two array:
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];
How can I get the following result?
aaa f1, aaa f2, aaa f3, bbb f1, bbb f2, bbb f3
let array1 = ["aaa", "bbb"];
let array2 = ["f1", "f2", "f3"];
const newArray = [];
array1.forEach(item1 => {
array2.forEach(item2 => {
newArray.push(item1 + " " + item2)
})
})
console.log(newArray);
Here's a solution using Array.prototype.flatMap()
and Array.prototype.map()
:
const array1 = ["aaa","bbb"];
const array2 = ["f1","f2","f3"];
const result = array1.flatMap(v1 => array2.map(v2 => `${v1} ${v2}`));
console.log(result);
let array1 = ["aaa", "bbb" ];
let array2 = ["f1","f2","f3"];
let response=[];
array1.forEach( ele1 => {
array2.forEach( ele2=> {
response.push( ele1 +' '+ ele2 );
})
});
console.log( response );
'use strict';
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];
let res = [];
array1.forEach( a1 => array2.forEach(a2 => res.push([`${a1} ${a2}`])) );
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];
let array3 = []
for (ele1 of array1) {
for (ele2 of array2) {
array3.push(ele1 + ' ' + ele2);
}
}
You could use reduce()
and map()
to achieve required result by using with Spread_syntax.
Please check below code snippet:
let array1 = ["aaa","bbb"],
array2 = ["f1","f2","f3"];
let result = array1.reduce((r,v)=>[...r,array2.map(m=>`${v} ${m}`).join(',')],[])
console.log(result.join(','))
With Loop
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];
let temp =[];
let index=0;
for(let i=0;i<array1.length;i++) {
for(let j=0;j<array2.length;j++) {
temp[index] = `${array1[i]} ${array2[j]}`;
index++;
}
}
console.log(temp);
With For Each
array1.forEach(item1 => {
array2.forEach(item2 => {
tempNew.push(item1 + " " + item2)
})
})
console.log(tempNew);
JSFiddle Fiddle
You can use Array.prototype.reduce() combined with Array.prototype.map(), spread syntax and template literals
Code:
const array1 = ["aaa", "bbb"];
const array2 = ["f1", "f2", "f3"];
const result = array1.reduce((a, c) => [...a, ...array2.map(f => `${c} ${f}`)], []);
console.log(result);