2

I'm mapping some points as dots onto a canvas, and I want dots which are repeats to be rendered as larger dots.

I need to check to see if the coordinate has already been mapped before, so I want to store the coordinates in an array as I go.

Here's what I have. I'm unsure about the .inArray line. How do I check to see if the coordinate is already in the array?

$(function() {
  var arr = [];
  arr.push([0,1]);
  arr.push([2,1]);
  arr.push([3,1]);
  arr.push([4,1]);
  arr.push([5,1]);

  if(jQuery.inArray("2,1",arr)) {
    alert("not there");
  }

});

HERE'S A SIMPLIFIED FIDDLE.

Jon
  • 3,154
  • 13
  • 53
  • 96
  • Does your code work or not work? If it doesn't work, what are the errors or problems that you are encountering? – Lee Taylor Jan 15 '13 at 20:57
  • How accurate (to how many decimal places) are those coordinates? You might just need to round them off using [`toFixed`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed) before pushing them onto your coordinates array. – Blazemonger Jan 15 '13 at 20:59
  • It does not work. And I'm pretty sure the coordinates are floating point values. They're coming from Twitter tweet data. It'd be ideal if the coordinates "matched" if they were +/- a few coordinate degrees. I posted a Fiddle. – Jon Jan 15 '13 at 21:00

2 Answers2

2

As far as I know, inArray only tests for simple values (i.e. not arrays or objects). You can use filter instead: Fiddle

 var arr = [];
  arr.push([0,1]);
  arr.push([2,1]);
  arr.push([3,1]);
  arr.push([4,1]);
  arr.push([5,1]);

x=2;
y=1;
    var filtered = $(arr).filter(function(){
        thisX = this[0];
        thisY= this[1];
        return x==thisX && y==thisY; 
    });
    if(filtered.length > 0){
       alert("yes"); 
    }
    else {
      alert("no");
    }

To test for range change the return condition like so:

return (x>thisX-0.5 && x<thisX+0.5) && (y>thisY-0.5 && y<thisY+0.5);
Matanya
  • 6,233
  • 9
  • 47
  • 80
0

After debugging your fiddle, it appears the problem has to do with how JavaScript tests for equality -- two arrays of the same length with identical elements in the identical order are still not considered "strictly equal" (===).

To work around this, you'll have to develop your own function for testing equality.

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180