- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Absolute difference of corresponding digits in 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 and 678

Then the digit distance will be −

|3-6| + |4-7| + |5-8| = 3 + 3 + 3 = 9

Therefore, let’s write the code for this function −

## Example

The code for this will be −

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

The output in the console will be −

9

- Related Questions & Answers
- Absolute difference of Number arrays in JavaScript
- Absolute difference between the first X and last X Digits of N?
- Difference of digits at alternate indices in JavaScript
- Check whether the sum of absolute difference of adjacent digits is Prime or not in Python
- Product sum difference of digits of a number in JavaScript
- Equality of corresponding elements in JavaScript
- Maximum absolute difference of the length of strings from two arrays in JavaScript
- Difference between product and sum of digits of a number in JavaScript
- Absolute sum of array elements - JavaScript
- Maximum sum of absolute difference of any permutation in C++
- Longest subarray with absolute difference equal to some number in JavaScript
- Finding minimum absolute difference within a Binary Search Tree in JavaScript
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1 in C++
- Number difference after interchanging their first digits in JavaScript
- Comparing corresponding values of two arrays in JavaScript

Advertisements