简体   繁体   中英

javascript replace first array value with second array value. First array length is 2 and second one length is 7

I have two arrays a and b and i need to replace array b value with a.

a= [1,2];
b=[1,2,3,4,5,6,7];

Expected output should be like this

[1,2,1,2,1,2,1]

Simply

var output = b.map( function(item, index){
  return a[ index % a.length ]
});

Demo

 var a= [1,2]; var b=[1,2,3,4,5,6,7]; var output = b.map( function(item, index){ return a[ index % a.length ] }); console.log( JSON.stringify( output ) )

You could take the index of the target array and map the value of source array with the index and remainder operator for the given length.

 var a = [1, 2], b = [1, 2, 3, 4, 5, 6, 7]; b = b.map((_, i) => a[i % a.length]); console.log(b);

You can use forEach to change the array in place and modulo to get the right index. You also can use map on the array if you want a new one.

 var a = [1,2] var b = [1,2,3,4,5,6,7] var l = a.length b.forEach((el,idx,arr) => { arr[idx] = a[idx%l] }) console.log(b)

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