Files
30-seconds-of-code/snippets/euclideanDistance.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

624 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
euclideanDistance math,algorithm,intermediate 2020-12-28T13:41:19+02:00 2020-12-28T13:41:19+02:00

Calculates the distance between two points in any number of dimensions.

  • Use Object.keys() and Array.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.
const euclideanDistance = (a, b) =>
  Math.hypot(...Object.keys(a).map(k => b[k] - a[k]));
euclideanDistance([1, 1], [2, 3]); // ~2.2361
euclideanDistance([1, 1, 1], [2, 3, 2]); // ~2.4495