Evaluating the distances among various points

Using the Pythagorean Theorem, I aim to calculate the distance between a series of points in an array by iterating through them and identifying the n closest points. However, I'm struggling to determine how to compute the distance (d) between each iterated point and the subsequent points for comparison. Let's start with the initial array of points:

 var points = [
   { id: 1, x: 0.0, y: 0.0 },
   { id: 2, x: 10.1, y: -10.1 },
   { id: 3, x: -12.2, y: 12.2 },
   { id: 4, x: 38.3, y: 38.3 },
   { id: 5, x: 79.0, y: 179.0 },
 ];

To proceed, I need to iterate through the points and create a new array that contains the distances between each point and all other points utilizing the Pythagorean theorem:

points.forEach((item) => {
  var newArray = [item];
  var pt = null;
  var d = null;
  for (var i = 0; i < points.length; i = i + 1) {
      //compare this point with all other points 
      for (var j = i + 1; j < points.length; j = j + 1) {
          //calculate distance 
          var curr = Math.sqrt(Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2));
       //record distance between each pair of points in a new array  
          if (d === null || curr < d) {                 
            o = points.id[i];     
            pt = points.id[j];
            d = curr; 
          }
       }
     }    
  newArray.push = {
   "id": o,
   "pt": pt,
   "d": d
  };
  console.log(newArray);
});

I've been encountering errors like

Cannot read property '0' of undefined
, suggesting there could be a flaw in my logic. Any advice on what might be going wrong here?

Answer №1

Currently, you are looping over each item three times: using a combination of forEach with nested for loops. Additionally, your attempts to perform calculations on points[i][0] and points[j][0] are incorrect as points[j] is an object with properties x and y, not an array with numeric indices.

A clearer approach would be to assign variables to each point and utilize the exponentiation operator:

var points = [
  { id: 1, x: 0.0, y: 0.0 },
  { id: 2, x: 10.1, y: -10.1 },
  { id: 3, x: -12.2, y: 12.2 },
  { id: 4, x: 38.3, y: 38.3 },
  { id: 5, x: 79.0, y: 179.0 },
];

const pointPairs = [];
for (let i = 0; i < points.length; i = i + 1) {
  const p1 = points[i];
  for (let j = i + 1; j < points.length; j = j + 1) {
    const p2 = points[j];
    const distance = Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
    pointPairs.push({ p1: p1.id, p2: p2.id, distance });
  }
}
pointPairs.sort((a, b) => a.distance - b.distance);
console.log(pointPairs.slice(0, 5));

You can achieve even cleaner code by utilizing array methods:

var points = [
  { id: 1, x: 0.0, y: 0.0 },
  { id: 2, x: 10.1, y: -10.1 },
  { id: 3, x: -12.2, y: 12.2 },
  { id: 4, x: 38.3, y: 38.3 },
  { id: 5, x: 79.0, y: 179.0 },
];

const pointPairs = [];
points.forEach((p1, i) => {
  points.slice(i + 1).forEach(p2 => {
    const distance = Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
    pointPairs.push({ p1: p1.id, p2: p2.id, distance });
  });
});
pointPairs.sort((a, b) => a.distance - b.distance);
console.log(pointPairs.slice(0, 5));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to handle the completion of the mongoose .exec function?

I am a bit confused about asynchronous code in Node.js and Mongoose. In simple terms, I want to post an array of usernames and check if each username is in the database. If it is, I want to add it to the valid array, otherwise, add it to the invalid array. ...

Convert a sentence into a character array in C++

Is there a way to input a sentence with spaces and uppercase and lowercase letters into a char array without using the cstring library? #include <iostream> using namespace std; int palindrome(char arrC[], int indexS, int indexE) { if(inde ...

What is the best way to expand an object without including any null values?

Imagine a scenario where there is an object: var user = { "Name": "Dan", "Age": 27, "Hobbies": null }; and it needs to be merged with the following base object to ensure all necessary properties are present: var base = { "Name": nul ...

show various commands and outcomes of the getElementsByClassName() function

Can someone help me figure out how to use the "getElementsByClassName() Method" in JavaScript to change or display different colors? I am trying to change the background color to blue for the class "ex" and red for the class "example", but it's not wo ...

What is the best way to temporarily bold a cell item within a table row for a specified duration of time?

I am experiencing an issue with a section of my code where I am fetching values from the server and updating a table if a certain value is not present. Once the update is made, I want to visually notify the user by temporarily making the cell's value ...

showing a message in a pop-up alert box

$(document).ready(function(){ $(document).on('click', '#btnSave', function () { var fname = $("#fname").val(); var lname = $("#lname").val(); var email = $("#email").val(); var mobile = $("#mobile").val(); if(fname == ""){ alert(&apos ...

Distinct "namespaces" within HTML

Recently, I've encountered an issue with my application that is causing ID collisions. The application uses AJAX to dynamically load code snippets based on user demand. Although these snippets vary significantly, there are instances where a code snipp ...

Retrieve data from the redux store within the components nested under redux-simple-router

I am currently working on finding a way to access the redux store within a route in order to dispatch actions directly from that location. Below is an example of how my main Component is structured: class App extends Component { render() { return ( ...

Collection of strung items that require removal of strings

I am currently working with an array of string objects and need help with formatting them. creatingTaskMatrix(pages) { let allTasks = []; for (let i = 0; i < pages.length; i++) { const page = pages[i]; for (let j = 0; j < page.tasks.length; j+ ...

Calculating date differences with date-fns

I've been attempting to calculate the difference between two dates using date fns, but all I get is NaN as a result. import { format, differenceInCalendarDays, parseISO, formatDistance } from "date-fns"; import { ru } from 'date-fns/locale&apo ...

What is the best way to display a Bootstrap v4 modal box within a container div?

Exploring the capabilities of Bootstrap v4.0.0-alpha has been an exciting experience, but I have a specific requirement in mind: I want to place a modal box inside a container div instead of it covering the entire screen. https://i.sstatic.net/xyZ8X.jpg I ...

The technique of using Javascript x to escape characters is

I've come across a handful of other software programs that feature a similar construct: let str = '\x32\x20\x60\x78\x6e\x7a\x9c\x89'; As I experimented with the sequence of numbers and letters within ...

When an array containing translations with Hebrew characters is declared, the str_replace() function fails to properly replace the specified substrings

I am encountering an issue with replacing Hebrew words in a string using an array of key-value pairs. This solution works perfectly in English, but seems to fail when dealing with Hebrew text. The code for English: function replace_twophrase_words($string ...

What is the process for loading the chosen option JSON object from an array when a button is clicked?

I have a TypeScript file containing JSON objects that can be selected as options from a dropdown list. I am looking for guidance on how to load/instantiate the selected JSON object when the user clicks a button to proceed. Specifically, I would like to le ...

Untangling REGEX URLs for Effective Filtering

I am currently working on creating a filter for a video list. I have successfully put together a string that includes all the values selected by the user for filtering. Right now, I am passing this string as a parameter through the URL. For example: NOTE ...

Remove underscores from a project utilizing browserify

I am currently working on a npm project and trying to ensure it is browser-compatible with browserify. One of the dependencies in this project is underscore. In order to build the project using browserify without including underscore in the final file, I h ...

The webpage runs smoothly in the browser, but unfortunately displays a blank screen on mobile devices

I'm currently in the process of developing an app utilizing a combination of the Ionic Framework, Phonegap, and AngularJS. Within the app, I have a directive called Item. While this directive functions perfectly when testing the application on a brow ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

Is there a way to collapse just one specific row in Angular?

I am struggling to toggle only the selected row, any suggestions? Take a look at my code and demonstration here: https://stackblitz.com/edit/test-trainin-2-gv9glh?file=src%2Fapp%2Fapp.component.scss Currently, all rows are being toggled when clicked, but ...