'How can I check the distance between two objects that are within the same array?

   coinsToRender.slice(0, 2).forEach((coin, coinIndex) => {
            coin.draw()
            coin.name()
            coin.update()


            const dist = Math.hypot(coin.x - coin.y, coin.x - coin.y)
            console.log(dist)


        })

This is my code currently. Each rendered coin displays a ball inside a canvas. I want to be able to check the distances between each of those elements (balls) that are in an array. It's currently only between 2 for testing purposes but I will be removing that and reverting it back to 100 and eventually check the distances between all of them.

As you can see I currently am comparing one to itself. I had the idea to try to compare it to the coinIndex but that doesn't work. I've been staring at my code for hours; not sure what do it from here.

I don't know if the right thing to say is that I am trying to compare the distance of coin[0] and coin[1] because I want to compare the distances between all the coins eventually.



Solution 1:[1]

To approach such a problem it's always best to visualize it. In this case let's imagine an array of 4 coins:

coins= [1, 2, 3, 4];

Ultimately we want to check if any of those collide so basically we need to pick one and compare it's position with all the remaining elements. This needs to be repeated until we've reached the end of the array - 1.

First round: pick 1 -> compare with 2, 3 and 4

Second round: pick 2 -> don't compare with 1 and 2 (this happened in the first round) | compare with 3 and 4

Third round: pick 3 -> don't compare with 1, 2 and 3 (happened in first and second round) | compare with 4

This translates well to a nested for-loop - e.g.

let coins = [1, 2, 3, 4];
let firstCoin, secondCoin;
for (let a = 0; a < coins.length - 1; a++) {
  firstCoin = coins[a];
  for (let b = a + 1; b < coins.length; b++) {
    secondCoin = coins[b];
    console.log("compare ", firstCoin, " with " + secondCoin);
  }
}

Edit

Nothing is stopping you from using a forEach instead of a plain for-loop for the outer loop. The only trouble is that you're looping over a segment of the array and not entirely:

coinsToRender.slice(0, 2)

For this use-case the forEach method offers an additional third parameter which returns the array being processed by forEach.

So the forEach variant of my example above would look a little like this:

let coinsToRender = [1, 2, 3, 4, 5];
coinsToRender.slice(0, 4).forEach((coin, coinIndex, arr) => {
  for (let b = coinIndex + 1; b < arr.length; b++) {
    console.log("compare ", coin, " with " + arr[b]);
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1