Euclidean Distance Calculation in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of Euclidean Distance and implement a function that calculates the distance between two points in any number of dimensions. We will use JavaScript and some built-in methods such as Object.keys() and Math.hypot() to create the function. This lab will provide a hands-on experience in working with mathematical calculations and JavaScript methods.

Euclidean Distance Calculation

To calculate the distance between two points in any number of dimensions, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Object.keys() and Array.prototype.map() to map each coordinate to its difference between the two points.
  3. Use Math.hypot() to calculate the Euclidean distance between the two points.

Here's an example code snippet to help you get started:

const euclideanDistance = (a, b) =>
  Math.hypot(...Object.keys(a).map((k) => b[k] - a[k]));

You can try out the function using these sample inputs:

euclideanDistance([1, 1], [2, 3]); // ~2.2361
euclideanDistance([1, 1, 1], [2, 3, 2]); // ~2.4495

Summary

Congratulations! You have completed the Euclidean Distance lab. You can practice more labs in LabEx to improve your skills.