Absolute difference of Number arrays in JavaScript



Suppose, we have two arrays like these βˆ’

const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];

We are required to write a JavaScript function that takes in such two arrays and returns an array of absolute difference between the corresponding elements of the array.

So, for these arrays, the output should look like βˆ’

const output = [8,6,4,1,3,3];

We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array.

Therefore, let’s write the code for this function βˆ’

Example

The code for this will be βˆ’

const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];
const absDifference = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0));
      res[i] = el;
   };
   return res;
};
console.log(absDifference(arr1, arr2));

Output

The output in the console will be βˆ’

[ 8, 6, 4, 1, 3, 3 ]
Updated on: 2020-10-21T12:02:46+05:30

459 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements