0

I have a pattern that i have an global array and whenever it requires processing move it to a local array and manipulate it so as to keep the original array intact. It had tended to work well until now.

function updateSpend(dataspend,year){
  // moving data spend global spend 
  // the value data spend itself is created from another Global attribute in             //    
// calling class. Something like this **var loc = Object.create(spend);**
  globalSpend = dataspend;
  // After the subsequent for loop the value of the original reflects the change
  dataspend.forEach(function(d){
      var val  = d.values.filter(function(d){
        if(d.key === year.key)
          return false;
        return true;
      });
      d.values = val;
    })

    var UpdateSvg = 
    d3.selectAll(".rects")
    .data(dataspend);

    //UpdateSvg.exit().remove();


    var rectsAll = UpdateSvg.selectAll("rect")
                    .data(function(d){
      return d.values
    });


    rectsAll.exit().remove();
    rectsAll.append("rect");
    //UpdateSvg.exit().remove();

}

I checked numerous SO posts on how array assignment is a pass by reference and also tried Object.create and other options still the global array is getting reflected. Are there any operators to keep them independent?

Thanks, Veera

Veeraraghavan N
  • 839
  • 1
  • 10
  • 19
  • Assigning an object in Javascript (including Arrays) does NOT make a copy of the array. It merely makes two variables that both now point at the same array. – jfriend00 Feb 02 '15 at 04:12
  • I used slice as well. But i still get the same. I suspect d3 filter is causing the undesirable behavior. Without filter i don't see this issue happening. Can you suggest me what could be the issue? – Veeraraghavan N Feb 02 '15 at 05:11
  • You'd have to show the code you tried with `.slice()` that isn't working (you can add it to your question as an edit) and make sure you show what type all the relevant variables are (and how they are declared). `.slice()` makes a shallow copy of an array and it works every time if used properly. If your arrays aren't shallow, that could also be a problem. – jfriend00 Feb 02 '15 at 05:20

0 Answers0