# Absolute difference of Number arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

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 21-Oct-2020 12:02:46