0

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
  • 2
    Possible duplicate of [Cartesian product of multiple arrays in JavaScript](https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript) – LF00 Sep 20 '19 at 07:26

8 Answers8

5

let array1 = ["aaa", "bbb"];
let array2 = ["f1", "f2", "f3"];

const newArray = [];

array1.forEach(item1 => {
 array2.forEach(item2 => {
  newArray.push(item1 + " " + item2)
 })
})

console.log(newArray);
Mahmudur Rahman
  • 745
  • 5
  • 13
lukeskywaka
  • 231
  • 1
  • 6
2

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);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1
let array1 = ["aaa", "bbb" ];
let array2 = ["f1","f2","f3"];
let response=[];
array1.forEach( ele1 => {
 array2.forEach( ele2=> {
   response.push( ele1 +' '+ ele2 );
 })
});
console.log( response );
0
'use strict';
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];

let res = [];

array1.forEach( a1 => array2.forEach(a2 => res.push([`${a1} ${a2}`])) );
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
0
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];
let array3 = []
for (ele1 of array1) {
    for (ele2 of array2) {
        array3.push(ele1 + ' ' + ele2);
    } 
}
Divyesh Puri
  • 196
  • 8
0

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(','))
 
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
0

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

Kannan T
  • 1,639
  • 5
  • 18
  • 29
0

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);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46