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
1

8 Answers 8

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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 );

Comments

0
'use strict';
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];

let res = [];

array1.forEach( a1 => array2.forEach(a2 => res.push([`${a1} ${a2}`])) );

Comments

0
let array1 = ["aaa","bbb"];
let array2 = ["f1","f2","f3"];
let array3 = []
for (ele1 of array1) {
    for (ele2 of array2) {
        array3.push(ele1 + ' ' + ele2);
    } 
}

Comments

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(','))
 

Comments

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.