Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 787
cloude Avatar asked Nov 21 '20 18:11

cloude


2 Answers

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);
like image 104
Majed Badawi Avatar answered Nov 08 '22 21:11

Majed Badawi


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]]);
like image 28
Aplet123 Avatar answered Nov 08 '22 21:11

Aplet123