1

This is my object:

function Plane (x,z) {  
    this.x = x;
    this.z = z;
}

var plane = new Plane(0,50000);

I have an array with these objects:

planesArray.push(plane);

I have a point object:

function Point (x,z) {  
    this.x = x;
    this.z = z;
}

var point = new Point(0,-50000);

I need to check if in planesArray exist an object with the specific point, so to check if the values x and y of the point are equal to any of the planes in the array and, if NOT, to perform an action.

I am still a novice, I apologize if this question sounds dumb.

1
  • Now, is there a nice way do do the same but with 6 (or more) points, without repeating? Commented Feb 9, 2013 at 17:07

2 Answers 2

2

Loop through the array and return a boolean indicating whether or not there was found a Point object with those attributes. This example uses the .some method to perform this operation.

var found = planesArray.some(function(plane) {
    return plane.x === x && plane.y === y;
});

if (found) {

}

Update: Here is the same code as a function.

function found(list, x, y) {
    return list.some(function(plane) {
        return plane.x === x && plane.y === y;
    });
}
Sign up to request clarification or add additional context in comments.

10 Comments

For existence, .some is enough. Also, you need ===.
@pimvdb Thanks. I will incorporate that into my answer.
Just keep in mind, Array.prototype.some is not compatible with IE8 and under - kangax.github.com/es5-compat-table
The only answer given that didn't actually work across all browsers, and it was the answer that was accepted. Um...
@wxactly Have you read the About page: Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked. I realize this isn't cross browser, but if it's a viable and helpful solution to the OP then I see no reason to withhold my answer.
|
0
var point = new Point(0,-50000);
for(var i = 0; i < planesArray.length; i++) {
    var plane = planesArray[i];
    if(plane.x != point.x || plane.z != point.z) {
        //perform action
        //break; //optional, depending on whether you want to perform the action for all planes, or just one
    }
}

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.