Absolute difference of Number arrays in JavaScript

In JavaScript, calculating the absolute difference between corresponding elements of two arrays is a common operation. This involves subtracting elements at the same index positions and taking the absolute value of the result.

Suppose we have two arrays like these:

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

We need to create a function that returns an array of absolute differences between corresponding elements. For these arrays, the expected output should be:

[8, 6, 4, 1, 3, 3]

Using For Loop

The most straightforward approach uses a for loop to iterate through both arrays and calculate the absolute difference for each pair of elements:

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));
[ 8, 6, 4, 1, 3, 3 ]

Using Array.map() Method

A more functional approach uses the map() method, which is cleaner and more readable:

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

const absDifferenceMap = (arr1, arr2) => {
    return arr1.map((val, index) => Math.abs(val - (arr2[index] || 0)));
};

console.log(absDifferenceMap(arr1, arr2));
[ 8, 6, 4, 1, 3, 3 ]

Handling Different Array Lengths

When arrays have different lengths, we should handle missing elements properly:

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

const safeDifference = (arr1, arr2) => {
    const maxLength = Math.max(arr1.length, arr2.length);
    const result = [];
    
    for(let i = 0; i < maxLength; i++) {
        const val1 = arr1[i] || 0;
        const val2 = arr2[i] || 0;
        result.push(Math.abs(val1 - val2));
    }
    
    return result;
};

console.log(safeDifference(arr1, arr2));
[ 8, 6, 4, 4 ]

Comparison

Method Readability Performance Handles Different Lengths
For Loop Good Fast Yes (with || 0)
Array.map() Excellent Good Partially
Safe Method Good Good Yes

Conclusion

Use Math.abs() with array iteration to calculate absolute differences. The map() method provides cleaner code, while for loops offer better control over edge cases like different array lengths.

Updated on: 2026-03-15T23:19:00+05:30

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements