简体   繁体   English

混合数组值 javascript

[英]Mix array value javascript

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有什么办法可以混合嵌套数组所以 output 会像这样

red house, red roof, red wall, green house, green roof, green wall

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

A nested map() with 2 join() 's to make it a string带有 2 个join()的嵌套map()使其成为一个字符串

 const arr = [ [ 'red', 'green' ],['house','roof','wall']]; const res = arr[0].map(a => arr[1].map(b => `${a} ${b}`).join(', ')).join(', '); console.log(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM