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:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Object.keys()andArray.prototype.map()to map each coordinate to its difference between the two points. - 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.