Search code examples
javascriptarraysfor-looparray-merge

Javascript concat not working as expected - not merging


I'm trying to merge values from a for loop, however it is not merging them into a single array, it is creating separate arrays?

I'm really new to Javascript, so am probably misunderstanding how to use the concat function. I have inserted a simplified version of my script below, I want the output to have all the values in a single array. can anyone help point me in the right direction please?

The code

var fixed = document.getElementById('fixed');

var sections = document.getElementsByClassName('section');

for (i = 0; i < sections.length; i++) {
  var arr = [];

  arr = arr.concat(sections[i]);

  fixed.innerHTML = arr;
  console.log(arr);
}
<div class="fixed" id="fixed"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>


Solution

  • Declare array before for loop, set fixed.innerHtml after and read about javascript scope.

    var fixed = document.getElementById('fixed');
    
    var sections = document.getElementsByClassName('section');
    
    var arr = [];
    
    for (i = 0; i < sections.length; i++) {
      arr = arr.concat(sections[i]);
    }
    
    fixed.innerHTML = arr;
    <div class="fixed" id="fixed"></div>
    <div class="section"></div>
    <div class="section"></div>
    <div class="section"></div>
    <div class="section"></div>
    <div class="section"></div>