2

Here's the problem.

I have 2 arrays

Arrays :

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

I want to insert the arr2 elemments inside the arr1 every n step for example :

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

I have this function as a start point but I can't figure out how to solve my problem from : 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);

Thank you so much for helping

  • Please provide a runnable snippet so everyone can quickly test what your function is doing. – sjahan Sep 06 '19 at 14:45
  • @sjahan I have added the snippet – Rahmani Saif El Moulouk Sep 06 '19 at 14:50
  • Did you run it? – sjahan Sep 06 '19 at 14:50
  • @sjahan yes and it works – Rahmani Saif El Moulouk Sep 06 '19 at 14:52
  • So, to be clear: since the code in your snippet (rather unhelpfully) contains different data than the original example, what is the expected result based on that input in the snippet? Because to me it appears like it does what it's supposed to - the word "item" is inserted every 3rd record. If you want a different result, you'll tell need to explain what that result should be, and why – ADyson Sep 06 '19 at 14:54
  • You fixed it because a few minutes ago, it didn't work ;) – sjahan Sep 06 '19 at 14:55
  • @ADyson, no that's not what I looking for, and I want to insert other array elements not the `items` string, and when all items of the other array are inserted that it needs to stop – Rahmani Saif El Moulouk Sep 06 '19 at 14:57
  • ok. I see. So...what have you tried? Looking again I can see you simply pulled that code snippet from another question. have you made any attempt at all to resolve this yourself? It seems fairly clear you need to start by iterating through the items in the second array, and stopping when that's done. Even if you can't yet see your way to the full solution, it ought to be simple enough that you can at least make a start. – ADyson Sep 06 '19 at 14:57
  • P.S. I made an answer but frankly I'm a bit surprised you couldn't at least figure out the basic approach and try something out. The logic is far from complicated. – ADyson Sep 06 '19 at 15:05
  • Possible duplicate of [How to add item in array every x items?](https://stackoverflow.com/questions/48288068/how-to-add-item-in-array-every-x-items) – Narendra Jadhav Sep 06 '19 at 19:30

4 Answers4

2

This should get you on the right track. Note that this modifies the original arrays:

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);
Gavin
  • 2,214
  • 2
  • 18
  • 26
1

This is relatively simple to adapt:

1) set a counter to keep track of which items from the second array have been added

2) instead of simply adding "item" to the main array at the nth step, instead add the item from arr2 at the current count. Then increase the counter.

3) Change the if condition to ensure that it doesn't try to add more items than exist in arr2

Demo:

/**
     * Add an item to an array at a certain frequency starting at a given index
     * @param array arr - the starting array
     * @param array arr2 - the list of items 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, arr2, starting, frequency) {
      var arr2count = 0;
      for (var i = 0, a = []; i < arr.length; i++) {
        a.push(arr[i]);
        if ((i + 1 + starting) % frequency === 0 && arr2count < arr2.length) {
          a.push(arr2[arr2count++]);
          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];
    var arr2 = ['up', 'down', 'left', 'right'];
    arr = addItemEvery(arr, arr2, 0, 2);
    console.log(arr);
ADyson
  • 57,178
  • 14
  • 51
  • 63
0

try this:

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var arr2 = ['up', 'down', 'left', 'right'];
var step=2;
var j=0;
 for (var i = 0,result= []; i < arr1.length; i++) {
         result.push(arr1[i]);
           if ((i + 1) % step === 0 && arr2.length>j)  {
            result.push(arr2[j]);
            j++;
          } 
    }
           console.log(result);
becher henchiri
  • 618
  • 4
  • 10
0

I solved it that way

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

var new_array = [];
var temp = 2;
var aggEl = () => {
    for(let i = 0, k=0; i<arr.length; i++){
        if(i== temp && k<arr2.length){
            new_array.push(arr2[k]);// I put the element of second array in new array
            k++;// I increase 'k' of one
            temp= i+3;   //new temp increase 'i' of 3 for find the new position where I will put other element of second array
        }
        else{      
            new_array.push(arr[i]);      
        }
    }
    alert(new_array);
}
Anna Pe
  • 1
  • 1