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.

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.