0

All:

Suppose I have tons of points (x, y), could anyone show me a fast way(simple algorithm preferred) to remove the duplicated position value points in Javascript?

What I can think about is like: sort them by x and compare one by one.

Kuan
  • 11,149
  • 23
  • 93
  • 201
  • possible duplicate of [Unique values in an array](http://stackoverflow.com/questions/1960473/unique-values-in-an-array) – orlp Apr 13 '15 at 17:47
  • @orlp thanks for info. My case is a little(only a little) different, it is 2d value, could you show me how to choose the key? – Kuan Apr 13 '15 at 18:07

1 Answers1

1

What you seem to be looking for is some sort of HashSet for Javascript. Conveniently enough for our purposes, Javascript Objects behave enough like that to do what you want in a really simple way:

// Assuming points is an array of objects that look like {x:i, y:i}
var uniquePoints = {};
for (var i = 0; len = points.length; i < len; i++) {
    var point = points[i];
    uniquePoint[point.x + '_' + point.y] = point;
}

At the end of the for loop, you'll have an object containing all unique points.

xathien
  • 812
  • 7
  • 10
  • Thanks for help, I think my main problem is deciding what to use as key, cos I am not sure if the value participates in string concatenation is exactly same as the value used to do calculation. For example: is that possible that the one point is [3.14159263489574936...(suppose it is very long), 5.3498375498534...], and another point is very close to it. when concatenate them as string, their results will be both "3.1415926348957493_5.3498375498534", but actually I need to keep both points? – Kuan Apr 13 '15 at 18:27
  • Depending on your application's requirements for precision, I'd recommend using the `toFixed(precision)` function, which returns a string with the required precision. However, as far as I can tell, Javascript's `toString()` on a number does not lose any precision. – xathien Apr 13 '15 at 20:09