Arrange an array of points in order of increasing distance from a given point

Assistance Required! I am in need of your help. I have a point with fixed coordinates, such as {x:5, y:4}, and an array containing objects that represent points:

[{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}]

My objective is to arrange the array according to the distance from the mentioned point in ascending order sort it like this:

[{x: 6, y: 2}, {x: 2, y: 6}, {x: 7, y: 10}, {x: 11, y: 6}, {x: 14, y: 10}]

Could you please guide me on how to achieve this using JavaScript? Appreciate your assistance!

Answer №1

Here is a potential solution:

// Initializing reference point
const refPoint = {x:5, y:4};

// Array of points to be sorted
const pointsToSort = [{x:2, y:6},{x:14, y:10},{x:7, y:10},{x:11, y:6},{x:6, y:2}];

// Calculate squared distance between two points
const squaredDistance = (pointA, pointB) => (pointA.x - pointB.x)**2 + (pointA.y - pointB.y)**2;

// Sorting the array based on distance from the reference point
const result = pointsToSort.sort((pointA, pointB) => squaredDistance(refPoint, pointA) - squaredDistance(refPoint, pointB));

console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Answer №2

This version presents an alternative approach that avoids using the Math.sqrt function by utilizing the quadratic sum of the deltas.

const
   array = [{ x: 2, y: 6 }, { x: 14, y: 10 }, { x: 7, y: 10 }, { x: 11, y: 6 }, { x: 6, y: 2 }],
   point = { x: 5, y: 4 };

array.sort((a, b) =>
    (a.x - point.x) ** 2 + (a.y - point.y) ** 2 -
    (b.x - point.x) ** 2 + (b.y - point.y) ** 2
);

console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Issue with setting background image height to 100% or 100vh

Seeking help to address the issue of the URL field impacting the total height. Any assistance would be greatly appreciated. body,html { height:100% } Issue arises when there is a display in the address bar. .bg { min-height:100% background-size: cover; ...

An error has occurred in Node.js: SyntaxError - Unexpected token ]

Here is the code snippet I am working with: app.get("/posts/:slug", function(request, response) { var slug = request.params.slug; connection.query("SELECT * from `posts` WHERE slug = ?", [ slug ], function(err, rows) { var post = rows[]; ...

Is it possible to send data to the server in node.js before the page is loaded?

Once a user has logged in, their data is stored on the client side. There are certain pages that can be viewed without requiring a user to log in... For instance, I have created a route on node.js which generates a profile page based on a URL parameter. ...

Triggering a pop-up window to appear without user interaction on the specified date within the function

I am looking to automatically trigger a pop-up window when my website loads after a specific date that I define within a function. How can I set up the date function for this task? I want the pop-up window to appear automatically on 27/07/2011, and every ...

Changing a single array into a series of arrays

I'm attempting to reverse the flattening process of an array. The JSON array I have as input contains 4 elements: [ { "nestedObj": { "id":12 } }, { "nestedObj": { "id":555 } ...

Simple JavaScript File Loading without Rendering or Running Laravel 8 Bootstrap 5

Hey there, I just set up a fresh laravel and bootstrap project. All I've done so far is create a navigation bar. However, when I load the page, I noticed that the app.js file is loading but the CSS is not rendering properly because the app.css stylesh ...

Issues with the functionality of the map method in Javascript arrays

I have integrated Laravel and Vue.js to develop a chat application. To secure my response in Laravel, I implemented encryption to prevent unauthorized access from the console: public function get() { $contacts = User::where('id', '!=&ap ...

Access arrays/objects within main object using JavaScript's Object.keys()方法

Perhaps the title is a bit confusing, but I couldn't come up with a better way to phrase it. I have a function that determines the value of each property within a contact object and returns 'No Data' if the value is null/empty/undefined. Ho ...

Javascript code has been implemented to save changes and address resizing problems

Code Snippet: <script> function showMe(){ document.querySelector('#change').style.display = ''; document.querySelector('#keep').style.display = 'none' document.querySelector('#change1').style.d ...

Difficulty encountered when attempting to implement custom filtering based on condition in HTML using Angular

I'm still new to angular, so please bear with me if this question seems trivial. I have a collection of integers in my controller and I need to filter it to only show items that meet a certain condition. Initially, I attempted the following: <div ...

Tips for changing the state of a toggle button with JavaScript

I need help creating a toggle button. To see the code I'm working on, click here. In my JavaScript code, I am reading the value of a 'checkbox'. If the value is true, I add another div with a close button. When the close button is clicked, ...

How can I extract a substring using jQuery?

<script type="text/javascript"> $(function(){ $("a[rel='tab']").click(function(e){ e.preventDefault(); pageurl = $(this).attr('href'); $.ajax({url:pageurl+'?rel=tab',success: function(data){ $(&apos ...

GIF Embeds with a Discord.js Bot

My bot is currently sending random gifs, but they are not embedded. I would like to send random gifs with embeds instead. How can I achieve this? Here are the codes: if (msg.author.bot) return; if (msg.content.toLowerCase() === prefix + 'xgif&ap ...

The Autofocus feature in HTML5 is malfunctioning in Internet Explorer 9

I am currently working on a project for IE9, and I am having trouble with the HTML5 autofocus keyword not functioning as expected. Specifically, the autofocus feature that puts the cursor in the specified input field is not working in IE9 (and I am forced ...

Searching for two fields of an object in Angular using ng-repeat

Let's imagine we have this array $scope.myArr = [{ name: 'Marc Rasmussen', phone: 239470192, title: 'It Dude', description: 'Hello my name is Marc i am testing the fact that i can search for two fields in an o ...

Error occurred when transferring arrays from C to nasm causing segmentation fault

In my current project, I have a C program that involves calling a function implemented in nasm. The C-call: extern void calc(float *, float *, float *, float *); //... float *data1, *data2, *results1, *results2; data1 = (float *)malloc(MAX ...

Incorporate the select2 plugin into your AngularJS project for enhanced functionality

In my AngularJS application, I am utilizing the select2 plugin to showcase a list of entities (tags). This snippet shows part of my template: select.ddlTags(ui-select2="select2Options", multiple, ng-model="link.tags") option(ng-repeat="tag in tags", ...

Validating nested input body objects in NodeJS Express

Struggling with validating nested object request bodies using the "express-validator" package. Imagine a scenario where we are collecting user input with a body structured like this: { "general": { "sessionId": "a2957207-e033-49e7-b9da-1c5f946 ...

Creating a Javascript object from a JSON string

Looking for a way to convert a JSON string into a JavaScript object? You can make use of the following code snippet obtained from the server: JSON String: ["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI M ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...