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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28289{{"`Euclidean Distance Calculation in JavaScript`"}} javascript/data_types -.-> lab-28289{{"`Euclidean Distance Calculation in JavaScript`"}} javascript/arith_ops -.-> lab-28289{{"`Euclidean Distance Calculation in JavaScript`"}} javascript/comp_ops -.-> lab-28289{{"`Euclidean Distance Calculation in JavaScript`"}} javascript/array_methods -.-> lab-28289{{"`Euclidean Distance Calculation in JavaScript`"}} javascript/higher_funcs -.-> lab-28289{{"`Euclidean Distance Calculation in JavaScript`"}} javascript/spread_rest -.-> lab-28289{{"`Euclidean Distance Calculation in JavaScript`"}} end

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.

Other JavaScript Tutorials you may like