How to subtract elements of two arrays and store the result as a positive array 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.

Using for Loop with Math.abs()

The most straightforward approach uses a for loop to iterate through both arrays and calculate the absolute difference using Math.abs():

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 to transform each element:

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 Arrays of Different Lengths

When arrays have different lengths, we can handle the longer array by using the maximum length:

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

const absDifferenceFlexible = (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(absDifferenceFlexible(arr1, arr2));
[ 8, 6, 4, 5, 8 ]

Comparison of Methods

Method Readability Performance Handles Different Lengths
for loop Good Excellent With modification
Array.map() Excellent Good Limited to first array length

Conclusion

Both approaches effectively calculate absolute differences between array elements. Use map() for cleaner functional code, or the for loop for maximum performance and flexibility with different array lengths.

Updated on: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements