首页 > 解决方案 > 将数组项插入另一个数组第 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元素,例如:arr1n

/*
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);

非常感谢你的帮助

标签: javascriptarrays

解决方案


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

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);


推荐阅读