Reputation: 1054
I need to insert a new member into Javascript array after each nth member.
If I try iterating over array and inserting new members with array.splice()
, it doesn't work because any type of iterating loop relies on array length, which changes on every iteration. For example, i have array like:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
and want to make it like:
[1, 2, 'insert this', 3, 4, 'insert this', 5, 6, 'insert this', 7, 8, 'insert this', 9, 10, 'insert this']
If I try code below, I end up with empty array:
var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var itemIndex = 2; itemIndex < dataRow.length; itemIndex += 2) {
dataRow.splice(itemIndex, 0, 'insert this');
}
This question is not a duplicate of questions where people just wanted to get member of array or to insert it at one particular position. Problem is, how to do it at every nth position.
Upvotes: 0
Views: 842
Reputation: 662
var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var length = dataRow.length;
for (var i = 1; i <= length / 2; i++) {
dataRow.splice(i * 3 - 1, 0, 'insert this');
}
console.log(dataRow);
Hope this works!
Upvotes: 1
Reputation: 386883
You could iterate from the end and splice the extra item.
var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var itemIndex = Math.floor(dataRow.length / 2) * 2; itemIndex > 0; itemIndex -= 2) {
dataRow.splice(itemIndex, 0, 'insert this');
}
console.log(dataRow);
Upvotes: 1
Reputation: 3686
Simply change your code to this. Add 3 to itemIndex to account for 1 insertion as well.
var dataRow = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var itemIndex = 2; itemIndex < dataRow.length; itemIndex += 3) {
dataRow.splice(itemIndex, 0, 'insert this');
}
console.log(dataRow);
Upvotes: 3