Clustering an array of points based on their positions
JavaScript
var clustered = [];
var points = [
{name:'first', position:{x:100, y:100}},
{name:'second', position:{x:300, y:300}},
{name:'third', position:{x:100, y:100}},
{name:'fourth', position:{x:250, y:250}},
{name:'fifth', position:{x:300, y:300}},
{name:'sixth', position:{x:100, y:100}},
{name:'seventh', position:{x:300, y:300}},
];
function cluster() {
var point, cluster;
while(points.length) {
point = points.pop();
cluster = [];
for(var i=points.length-1;i>=0;i--) {
var target = points[i];
if(target.position.x == point.position.x && target.position.y == point.position.y) {
cluster.push(target);
points.splice(i,1);
}
}
if(cluster.length>0) {
cluster.push(point);
clustered.push(cluster);
}
else {
clustered.push(point);
}
}
}
cluster();
console.log(clustered); // Return two clusters (array of objects) and a lonely point (object)
/**
It must returns two clusters :
- 1: 'second', 'fifth' and 'seventh' share same position
- 2: 'first', 'third' and 'sixth' share same position
and a lonely point :
- 3: 'fourth'
**/