简体   繁体   中英

Merge two Javascript array with different sizes

Hi have two Javascript array:

var array1 = ['blue', 'red', 'gray', 'orange', 'violet', 'black', 'yellow', 'brown', 'white'];
var array2 = ['2', '3', '6', '8'];

merged arrays with:

var arr = arr_today_leads.map(
    (element, index) => [element, arr_online_op[index]]
).flat();

I'd like to have this result:

['blue', '2', 'red', '3', 'gray', '6', 'orange', '8', 'violet', '2', 'black', '3', yellow', '6, 'brown', '8', 'white', '2']

Instead of:

['blue', '2', 'red', '3', 'gray', '6', 'orange', '8', 'violet', 'undefined', 'black', 'undefined', yellow', 'undefined, 'brown', 'undefined', 'white', 'undefined']

thanks in advance!

You can use modulo:

 const arr_today_leads = ['blue', 'red', 'gray', 'orange', 'violet', 'black', 'yellow', 'brown', 'white']; const arr_online_op = ['2', '3', '6', '8']; const len = arr_online_op.length; const arr = arr_today_leads.map( (element, index) => [element, arr_online_op[index%len]] ).flat(); console.log(arr);

First of all, you can use flatMap instead of map then flat . Second of all, you need to wrap the index around with a modulo:

const arr = array1.flatMap((ele, i) => [ele, array2[i % array2.length]]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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