Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Javascript every() method to check one element against all other in an array?

My situation is this, I have a Point object thats has an 'x' and 'y' properties. Point also have a getDistance() method that calculates the distance between two Points.

Example:

if (position.getDistance(prevPosition) > 10) {
    // add new Point
} else {
    // don't add new Point
}

I have an array of Points and I need to check if the new Point is too close to all the other Points in the array. looking at the Javascript documentation the every() method seems to be the go to function to use but I'm struggling implementing it.

function getDistance(position, prevPosition) {
    return position.getDistance(prevPosition) > 10;
}

if (points.every(position)) {
    // add new Point
} else {
    // don't add Point
}

Any help will be much appreciated

like image 974
Ricardo Sanchez Avatar asked Jan 01 '26 03:01

Ricardo Sanchez


1 Answers

.every takes a function, and every element of the array gets passed to that function (in your case, every point gets passed) and then you have to return a predicate (whether it is far away):

  points.every(position => position.getDistance(newPoint) > 10)
like image 192
Jonas Wilms Avatar answered Jan 03 '26 15:01

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!