# Calculate distance in point collection algorithm

I've got collection of points which are sorted by x,y and distance between `n` and `n+1` (array of objects `[{x:0,y:0},{x:1,y:1}....]` I would like to calculate distance between all points (point 1 distance to all points, point 2 distance to all points and so on) and add weight to point depends of points in distance parameter (for ex. 500m). Can someone help me with algorithm, because below algorithm time is O(n^2) so maybe there is faster way than that..

``````_groupPoints : function(points) {
var points = points.sort(function(a, b) {
return Math.sqrt(Math.pow((a.y - b.y), 2) + Math.pow((a.x - b.x), 2));
}), tmp = [], idx = 0, length = points.length, i = 0, j = 1, res = 0;

tmp.push([points]);
idx = 0;
for (i; i < length; i++) {
j = i + 1;
for (j; j < length; j++) {
res = Math.sqrt(Math.pow((points[i].x - points[j].x), 2) + Math.pow((points[i].x - points[j].x), 2));
if (Math.floor((((res * Math.PI) / 180) * 40076000) / 400) <= 500) {
tmp[idx].push(points[j]);
}
}
idx++;
tmp[idx] = [points[j]];
}
}
``````