Reputation: 987
I want to split an array in n
parts where each part gets printed on a new line.
Let's say I have the following array which I need in chunks of five:
var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];
Then the desired result should be:
dog,bird,cat,bear,cow
fish,ape,worm,ant,fly
When I run this code I only seem to get the last chunk printed.
<p id="demo"></p>
<script>
var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];
var i,j,temparray,chunk = 5;
for (i=0,j=res.length; i<j; i+=chunk) {
temparray = res.slice(i,i+chunk) + "<br>";
document.getElementById("demo").innerHTML = temparray;
}
</script>
Upvotes: 0
Views: 114
Reputation: 1
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let idx = 0;
let count = 0;
let tempList = [];
let resultList = [];
let splitSize = 2
while (idx <= array.length)
{
tempList.push(array[idx++]);
count++;
if (count == splitSize)
{
resultList.push(tempList);
tempList = [];
count = 0;
}
}
if (!tempList.length)
{
resultList.push(tempList);
}
Upvotes: 0
Reputation: 171669
Destructive while loop approach
var res = ["dog", "bird", "cat", "bear", "cow", "fish", "ape", "worm", "ant", "fly"];
var chunks = [],chunk = 4;
while (res.length) {
chunks.push(res.splice(0, chunk).join(', '))
}
document.getElementById("demo").innerHTML = chunks.join('<br>');
<p id="demo"></p>
Upvotes: 1
Reputation: 66999
It would be more efficient to only write to innerHTML
just once, instead of updating it once per row of output (which would force the browser to update the display after every row). The for-loop in the following snippet just appends each row to the temparray
variable, and innerHTML
is updated just once -- after the for-loop.
var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];
var i,temparray = "", chunk = 5;
for (i=0; i < res.length; i+=chunk) {
temparray += res.slice(i,i+chunk) + "<br>";
}
document.getElementById("demo").innerHTML = temparray;
<p id="demo"></p>
Upvotes: 1
Reputation: 1799
You must concatenate to get the existing innerHtml already
document.getElementById("demo").innerHTML += temparray;
Upvotes: 4
Reputation: 5708
You forgot to add a +
to your document.getElementById("demo").innerHTML = temparray;
.
var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];
var i,temparray,chunk = 5;
for (i=0; i < res.length; i+=chunk)
{
temparray = res.slice(i,i+chunk) + "<br>";
document.getElementById("demo").innerHTML += temparray;
}
<p id="demo"></p>
Upvotes: 2