perrosnk
perrosnk

Reputation: 935

How to add item in array every x items?

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

Upvotes: 5

Views: 4888

Answers (3)

Negi Rox
Negi Rox

Reputation: 3932

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?

Upvotes: 0

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23389

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386746

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

Upvotes: 13

Related Questions