Number difference after interchanging their first digits in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of exactly two numbers. Our function should return the absolute difference between the numbers after interchanging their first digits.

For instance, for the array [105, 413],

The difference will be: |405 - 113| = 292

Example

Following is the code −

 Live Demo

const arr = [105, 413];
const interchangedDigitDiff = (arr = []) => {
   arr = arr.map(String);
   const [first, second] = arr;
   const fChar = first[0];
   const sChar = second[0];
   const newFirst = sChar + first.substring(1, first.length);
   const newSecond = fChar + second.substring(1, second.length);
   const newArr = [+newFirst, +newSecond];
   const diff = Math.abs(newArr[0] - newArr[1]);
   return diff;
};
console.log(interchangedDigitDiff(arr));

Output

Following is the console output −

292
raja
Updated on 19-Apr-2021 07:35:17

Advertisements