简体   繁体   中英

How to join elements of two different size arrays in javascript?

Would I like to create a new array from the following:

Let array1 = [a,b,c,d]
let array2 = [x, y]

How to get new array like this [ay,bx,cy,dx]?

Thanks,

You could take the index with an offset and the remainder of the length of the second array.

 let array1 = ['a','b','c','d'], array2 = ['x', 'y'], result = array1.map((v, i) => v + array2[(i + 1) % array2.length]); console.log(result);

You can use the modulus operator to get the correct second array elements:

 let array1 = ['a','b','c','d']; let array2 = ['x', 'y']; let result = array1.map( (item, i) => { return item + array2[(i+1) % 2] } ); console.log(result);

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