I would like to insert element into 2nd and 9th position of an array for every 10 elements and the length of array can be vary.
I tried to use mod but the element will be inserted multiple time within 10 elements.
Example:
var array = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6','a7', 'a8', 'a9', 'a10','a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19', 'a20', 'a21', 'a22', 'a23'];
Expected outcome (inserted b & c at position 2nd & 9th ):
[‘a1’, ‘b1‘, ‘a2’, ‘a3’, ‘a4’, ‘a5’, ‘a6′,’a7’, ‘c1‘, ‘a8’, ‘a9’, ‘b2‘, ‘a10′,’a11’, ‘a12’, ‘a13’, ‘a14’, ‘a15’, ‘c2‘, ‘a16’, ‘a17’, ‘b3‘, ‘a18’, ‘a19’, ‘a20’, ‘a21’, ‘a22’, ‘a23’];
How to achieve the result?
2
Answers
You can iterate over the array while adding elements with
Array#splice
.