Reputation: 990
I have an array with various paragraphs inside:
var content = [ "<p>This is a paragraph 1</p>",
"<p>This is a paragraph 2</p>",
"<p>This is a paragraph 3</p>",
"<p>This is a paragraph 4</p>",
"<p>This is a paragraph 5</p>" ]
I want to perform a simple operation on each element inside the array. Each paragraph needs to be placed inside a container and then be removed from the array. This is the corresponding HTML:
<div class="article">
<div id="cell1" class="text-block">
<div class="container"></div>
</div>
</div>
And this is how I am attempting to do what I describe above:
for (i = 0; i < content.length; i++) {
console.log("Current item: " + content[i])
//
var itemtoRemove = content[i];
$("#cell1 .container").append(content[i]);
//
content.splice($.inArray(itemtoRemove, content), 1)
}
I have put everything together in a fiddle as well: https://jsfiddle.net/johschmoll/1mjzu4qg/71/
Basically, everything is working fine, but the for-statement seems to be skipping every second element in the array. I cannot figure out the reason, even after looking at similar cases. What am I doing wrong here?
Upvotes: 0
Views: 78
Reputation: 24965
Since you are modifying the array as you loop, use a while loop that checks that the array is not empty
while (content.length) {
console.log("Current item: " + content[0])
//
var itemtoRemove = content[0];
$("#cell1 .container").append(content[0]);
//
content.shift();
}
Keeping in mind that if all you are doing is appending all the elements, then this is unnecessary. append()
can accept an array
$("#cell1 .container").append(content.splice(0));
Upvotes: 3
Reputation: 65853
Because you are modifying the array upon each iteration, the length of the array changes and you wind up skipping items. Instead, loop through the array backwards to avoid the issue.
var content = [ "<p>This is a paragraph 1</p>",
"<p>This is a paragraph 2</p>",
"<p>This is a paragraph 3</p>",
"<p>This is a paragraph 4</p>",
"<p>This is a paragraph 5</p>" ]
for (var i = content.length-1; i >= 0 ; i--) {
console.log("Current item: " + content[i])
var itemtoRemove = content[i];
$("#cell1 .container").append(content[i]);
content.splice($.inArray(itemtoRemove, content), 1)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="article">
<div id="cell1" class="text-block">
<div class="container"></div>
</div>
</div>
Upvotes: 1