0

I have an array which has nested array like this

const arr = [[red,green],[house,roof,wall]]

Is there any way to mix the nested array so output will be like this

red house, red roof, red wall, green house, green roof, green wall
Saral Karki
  • 4,530
  • 2
  • 7
  • 10
  • 2
    Are you after [Cartesian product of multiple arrays in JavaScript](https://stackoverflow.com/q/12303989)? – VLAZ May 04 '22 at 09:43

2 Answers2

2

Please check below code

const arr = [['red','green'],['house','roof','wall']];
const array1 = arr[0];
const array2 = arr[1];
const new_arr = [];
for(let i=0; i< array1.length; i++){
    for(let j=0; j< array2.length; j++){
        new_arr.push(array1[i] + ' ' +array2[j]);
    }
}
console.log(new_arr); 
// output ['red house', 'red roof', 'red wall', 'green house', 'green roof', 'green wall']
console.log(new_arr.join(',')); 
// output: red house, red roof, red wall, green house, green roof, green wall
N.S
  • 139
  • 1
  • 1
  • 13
1

A nested map() with 2 join()'s to make it a string

const arr = [ [ 'red', 'green' ],['house','roof','wall']];

const res = arr[0].map(a => arr[1].map(b => `${a} ${b}`).join(', ')).join(', ');

console.log(res);
0stone0
  • 34,288
  • 4
  • 39
  • 64