Calculating Euclidean Vector Distance in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will dive into the world of JavaScript programming and explore the concept of vector distance. The purpose of the lab is to help you understand how to use Array.prototype.reduce(), Math.pow(), and Math.sqrt() to calculate the Euclidean distance between two vectors. By the end of the lab, you will have gained practical experience in implementing this useful function in JavaScript.


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`") subgraph Lab Skills javascript/variables -.-> lab-28692{{"`Calculating Euclidean Vector Distance in JavaScript`"}} javascript/data_types -.-> lab-28692{{"`Calculating Euclidean Vector Distance in JavaScript`"}} javascript/arith_ops -.-> lab-28692{{"`Calculating Euclidean Vector Distance in JavaScript`"}} javascript/comp_ops -.-> lab-28692{{"`Calculating Euclidean Vector Distance in JavaScript`"}} javascript/array_methods -.-> lab-28692{{"`Calculating Euclidean Vector Distance in JavaScript`"}} javascript/higher_funcs -.-> lab-28692{{"`Calculating Euclidean Vector Distance in JavaScript`"}} end

Vector Distance Calculation

To calculate the distance between two vectors, follow these steps:

  1. Open the Terminal/SSH to start practicing coding.
  2. Type node to begin.
  3. Use Array.prototype.reduce(), Math.pow(), and Math.sqrt() to find the Euclidean distance between the vectors.
  4. Apply the vectorDistance formula, shown below:
const vectorDistance = (x, y) =>
  Math.sqrt(x.reduce((acc, val, i) => acc + Math.pow(val - y[i], 2), 0));
  1. Test the formula by entering two vectors in the following format: vectorDistance([10, 0, 5], [20, 0, 10]);
  2. The output will be the distance between the two vectors: 11.180339887498949.

Summary

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

Other JavaScript Tutorials you may like