Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 316
perrosnk Avatar asked Jan 16 '18 18:01

perrosnk


People also ask

How do you add an item to an array of objects?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.

How do you add all values in an array together?

To get the sum of an array of numbers:Use the Array. reduce() method to iterate over the array. Set the initial value in the reduce method to 0 . On each iteration, return the sum of the accumulated value and the current number.

What is every () in JavaScript?

The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.


1 Answers

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; }
like image 180
Nina Scholz Avatar answered Sep 26 '22 14:09

Nina Scholz