5

How can I add an item every x item in an array? For example I would like to add an item every 10 items in the 3rd position:

const arr = [1,2];
const result = [1,2, item];

or

const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
const result = [1,2,item,3,4,5,6,7,8,9,10,11,item,12,13,14,15,16];
perrosnk
  • 835
  • 2
  • 13
  • 23

3 Answers3

13

You could take a while loop and check the length after taking the starting position and the interval length as increment value.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
    pos = 2;
    interval = 10;
    
while (pos < array.length) {
    array.splice(pos, 0, 'item');
    pos += interval;
}

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    This adds an item after 2, then 9, then 8 and so on. This is because you are changing the size of the array as you add to it. You will need to add an offset to interval on each splice. – newmaniese Aug 13 '20 at 11:50
1

Here's an option that doesn't alter the original array.. just loop and insert to a new array.

/**
 * 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", 2, 3);
console.log(arr);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
0

Use arr.splice method. Calculate index for every tenth element like 2,12,22...

var arr = [];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

For more reference How to insert an item into an array at a specific index?

Negi Rox
  • 3,828
  • 1
  • 11
  • 18