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]]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With