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.

3
  • Does your code work or not work? If it doesn't work, what are the errors or problems that you are encountering? Commented Jan 15, 2013 at 20:57
  • How accurate (to how many decimal places) are those coordinates? You might just need to round them off using toFixed before pushing them onto your coordinates array. Commented Jan 15, 2013 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. Commented Jan 15, 2013 at 21:00

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

This seems to work best. How can I alter this to check if the values are within +/- 2 coordinate degrees? So if [1.5,2,0] is stored, then with +/- 0.5 [1.1, 1.8] would match?
You should not use .filter() in non-jQuery objects
Is there an alternative, Alex?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.