0

I'm filtering an array which forms a set of markers on a Google Map (API V3) here: http://testdae.dialanexchange.com/testmap.aspx.

It all works in combination correctly for either of Timeshare Resorts and Private Properties with either or both of Disabled Access and Allow Pets. In all these cases the debug alert I've put in shows 1642 which is the number of points in the original array used for the markers.

However, when you select All and either or both of Disabled Access and Allow Pets, after it has correctly displayed the result, deselecting either of the checkboxes results in the alert showing that these filters have affected the original array as it indicates the number of the Total at the bottom of the filter section. It can only be reset by reloading the page.

I think the issue is in the filterProperties() function but I can't see it.

Is there something I'm missing here because I've been staring at it, Googling and trying various things to get it to work for over a day now? I thought $.grep wasn't supposed to affect the original array.

Craig
  • 1,704
  • 1
  • 18
  • 36

2 Answers2

3

From the jQuery documentation of $.grep():

Finds the elements of an array which satisfy a filter function. The original array is not affected.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
  • 3
    That looks like a very nice RTFM to me :p – Niet the Dark Absol Jul 14 '12 at 13:49
  • That is indeed what the documentation says. But is it the case in practice in this instance. I'm taking an original array called "data", filtering it into a new array called "newData" using filterProperties() which is then filtered again by filterDisabledAccess(). At this point the original array "data" appears to have been altered. – Craig Jul 14 '12 at 13:51
  • @Craig it's happening somewhere else, not `$.grep` – Esailija Jul 14 '12 at 13:57
  • @Esailija - Ok, the question title is probably misleading. But, even more Googling has come up with the solution. It's the newData = data; line. If you assign an object to an object then they're assigned by REFERENCE to the same object. So thanks to http://od-eon.com/blogs/bogdan/javascript-assignment-reference-vs-object-cloning/ cloning the data to newData solved the issue. – Craig Jul 14 '12 at 14:20
0

The answer turned out to be that it wasn't $.grep that was at fault but that assigning an object to another object in Javascript causes both objects to be altered if one is, as they're linked by reference to the same object. The solution was to clone a new object from the original, thus maintaining the integrity of the original object. References are:-

1) What is the most efficient way to deep clone an object in JavaScript?

2) http://od-eon.com/blogs/bogdan/javascript-assignment-reference-vs-object-cloning/

Community
  • 1
  • 1
Craig
  • 1,704
  • 1
  • 18
  • 36