Search code examples
javascriptjqueryarrayscoords

How can I add/remove element/s by coords from array with javascript?


I would like to know a way to get coordinates from array, check if element exist at these coords and create it if it doesn't.

This is for an upcoming nodejs game. I have tried a couple of techniques, but all ends with a nested code and overall slow performance

For the sake of this question let's assume I have this array of objects or it can also comes from a json file doesn't really matter as long as it works as expected.

{
 id: 1,
 left: 60,
 top: 10,
 free: 1
},
 id:2 ,
 left: 120,
 top: 10:,
 free: 0
}

And I have a simple container like so

<div style="width: 1000px; height: 300px; background: red;"></div>

Now imagine a grid of 5 in-line 60x50 boxes where id:1 is the first box and id:2 is the 2nd box. How can I check if element/div exist in the grid box 1 or 2 and if there is any, update free: to 1(exist) or 0(doesn't exist) in the array for the specific id?


Solution

  • One solution i can think of is, put an Id inside a div when rendering like for example, you have id=1,2 in your json and you have 5 boxes in your view, inside each box if you render a div, give it an id and then use jquery to find a div like here : How to find a particular Div using jQuery

    Or if you cannot put id on div, put a id on the top element(supposing it is div) of the box, find the box and try finding the required div inside that box element div.

    Hope this helps.