Subtract Elements of Two 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 two such arrays and returns an array of absolute difference between the corresponding elements of the array.

Therefore, 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.

Example

Following is the code −

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

This will produce the following output in console −

[ 8, 6, 4, 1, 3, 3 ]
Updated on: 2020-09-18T13:27:01+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements