
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Digit distance of two numbers - JavaScript
We are required to write a JavaScript function that takes in two numbers a and b returns their digit distance.
Digit distance
The digit distance of two numbers is the absolute sum of the difference between their corresponding digits.
For example: If the numbers are −
345 678
Then the digit distance will be −
|3-6| + |4-7| + |5-8| = 3 + 3 + 3 = 9
Example
Following is the code −
const num1 = 345; const num2 = 678; const digitDistance = (a, b) => { const aStr = String(a); const bStr = String(b); let diff = 0; for(let i = 0; i < aStr && i < bStr.length; i++){ diff += Math.abs(+(aStr[i] || 0) - +(bStr[i] || 0)); }; return diff; }; console.log(digitDistance(num1, num2));
Output
Following is the output in the console −
9
- Related Articles
- Finding the nth digit of natural numbers JavaScript
- Finding nth digit of natural numbers sequence in JavaScript
- Find the largest palindrome number made from the product of two n digit numbers in JavaScript
- How many numbers of two digit are divisible by 3?
- Sorting numbers according to the digit root JavaScript
- 8085 Program to multiply two 2-digit BCD numbers
- How many two digit numbers are divisible by $3?$
- Sorting numbers based on their digit sums in JavaScript
- Finding sequential digit numbers within a range in JavaScript
- The HCF and LCM of two numbers are 9 and 819 respectively. One of the numbers is a two-digit number. Find the numbers.
- Find how many two-digit numbers are divisible by 6.
- Counting n digit Numbers with all unique digits in JavaScript
- Hamming Distance between two strings in JavaScript
- Find the minimum distance between two numbers in C++
- Count of N-digit Numbers having Sum of even and odd positioned digits divisible by given numbers - JavaScript

Advertisements