javascript - 将数组项插入另一个数组第 n 个元素
问题描述
这就是问题所在。
我有 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'];
我想在每个步骤中插入arr2
元素,例如:arr1
n
/*
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];
我有这个功能作为起点,但我不知道如何解决我的问题:如何在数组中添加每 x 个项目的项目?
/**
* 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);
推荐阅读
- marklogic - 光学 API:如何获取具有最大值的列的值?
- javascript - How to track user interaction with a video using JS?
- python - DataFrame 每一行的值的总和
- python - 在数据框的单元格内插入列表
- angular - 错误:运行 Protractor 端到端测试时找不到 update-config.json
- javascript - Gulp 重新处理未更改的文件
- python - 合并多个表 - pd.concat: append vs yield
- javascript - 如何使用 nodejs 在我的控制台中打印 Mongodb 的更新文档?
- javascript - 如何在字段集中显示 lat 和 lng 坐标()?
- python - 从现在到下一个小时的第 0 分钟的时间