[英]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 和 b,我需要用 a 替换数组 b 的值。
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.您可以使用 forEach 就地更改数组并取模以获得正确的索引。 You also can use map on the array if you want a new one.
如果你想要一个新的,你也可以在数组上使用 map。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.