Arihant Arihant - 1 year ago 71
Javascript Question

Loop logic for drawing line javascript

I have following two arrays:

var element_1 = new Array([x1,y1],[x2,y2],[x3,y3],[x4,y4]);
var element_2 = new Array([x1,y1],[x2,y2],[x3,y3],[x4,y4]);

I want to run a loop (nested) where each element of
(for eg
) is compared to each element of
and the shortest distance between them shall be calculated within the loop (I know how to calculate the shortest path). The tricky part here is that I need a reference that which pair made the shortest past and then obtain those
combinations to draw a line.

Sample data:

var element_1 = new Array([10,0],[20,10],[10,20],[0,10]);
var element_2 = new Array([10,30],[20,40],[10,50],[0,40]);

Line should be made between [10,20] and [10,30]. Also, I would somehow need to store the coordinates somewhere to pass it to the line drawing function

How can I do this? Any leads would be highly appreciated.

Answer Source

Here is how I would do it:

var element_1 = [[0,0],[1,2],[5,3],[6,8]];
var element_2 = [[0,1],[1,4],[5,9],[9,8]];

var closest = {a: false, b: false, distance: false};

for(var i=0; i<element_1.length; i++) {
  for(var j=0; j<element_2.length; j++) {
    var distance = calculate_distance(element_1[i], element_2[j]);
    console.log('Distance between element_1['+i+'] and element_2['+j+']: ' + distance);
    if(closest.distance === false || distance < closest.distance) {
      closest = {a: element_1[i], b: element_2[j], distance: distance};

console.log('The shortest path is between '+closest.a+' and '+closest.b+', which is '+closest.distance);

function calculate_distance(a, b) {
  var width  = Math.abs( a[0] - b[0] ),
      height = Math.abs( a[1] - b[1] ),
      hypothenuse = Math.sqrt( width*width + height*height );
  return hypothenuse;

As Roko C. Buljan said, in your case you can just replace new Array() with []. Here's why.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download