gpt4 book ai didi

javascript - 将数组项插入另一个数组中的第 n 个元素

转载 作者:行者123 更新时间:2023-11-28 03:35:02 27 4
gpt4 key购买 nike

问题来了。

我有2个数组

数组:

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var arr2 = ['up', 'down', 'left', 'right'];

我想在每个 n 步的 arr1 中插入 arr2 元素,例如:

/*
If the step is 2 the result would be :
*/
[1,2,'up',3,4,'down',5,6,'left',7,8,'right',9, 10, 11, 12, 13, 14, 15, 16];

我以这个函数为起点,但我不知道如何解决我的问题:How to add item in array every x items?

/**
* Add an item to an array at a certain frequency starting at a given index
* @param array arr - the starting array
* @param mixed item - the item to be inserted into the array
* @param integer starting = the index at which to begin inserting
* @param integer frequency - The frequency at which to add the item
*/
function addItemEvery(arr, item, starting, frequency) {
for (var i = 0, a = []; i < arr.length; i++) {
a.push(arr[i]);
if ((i + 1 + starting) % frequency === 0) {
a.push(item);
i++;
if(arr[i]) a.push(arr[i]);
}
}
return a;
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
arr = addItemEvery(arr, "item", 0, 3);
console.log(arr);

非常感谢您的帮助

最佳答案

这应该会让你走上正轨。请注意,这会修改原始数组:

let arr1 = [1,2,3,4,5,6,7,8,9];
let arr2 = ['up', 'down', 'left', 'right'];
let nth = 2;
let result = arr1.reduce((carry, current_value, index, original)=>{
// insert current element of arr1
carry.push(current_value);
// insert from arr2 if on multiple of nth index and there's any left
if((index+1) % nth === 0 && arr2.length!=0){
carry.push(arr2.shift())
}
return carry;
}, []);
console.log('result', result);

关于javascript - 将数组项插入另一个数组中的第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57824156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com