Compare two arrays of single characters and return the difference? JavaScript

We are required to compare, and get the difference, between two arrays containing single character strings appearing multiple times in each array.

Example of two such arrays are:

const arr1 = ['A', 'C', 'A', 'D'];
const arr2 = ['F', 'A', 'T', 'T'];

We will check each character at the same position and return only the parts who are different.

Approach

The algorithm compares elements at the same index position. When characters differ, both are added to the result array. Any remaining elements from the longer array are also included.

Example

const arr1 = ['A', 'C', 'A', 'D'];
const arr2 = ['F', 'A', 'T', 'T'];

const findDifference = (arr1, arr2) => {
    const min = Math.min(arr1.length, arr2.length);
    let i = 0;
    const res = [];
    
    while (i < min) {
        if (arr1[i] !== arr2[i]) {
            res.push(arr1[i], arr2[i]);
        }
        ++i;
    }
    
    return res.concat(arr1.slice(min), arr2.slice(min));
};

console.log(findDifference(arr1, arr2));
[
  'A', 'F', 'C',
  'A', 'A', 'T',
  'D', 'T'
]

How It Works

The function follows these steps:

  1. Find the minimum length between both arrays
  2. Compare elements at each position up to the minimum length
  3. When elements differ, add both to the result array
  4. Append any remaining elements from the longer array

Different Array Lengths Example

const arr3 = ['X', 'Y'];
const arr4 = ['X', 'Z', 'A', 'B'];

console.log(findDifference(arr3, arr4));
[ 'Y', 'Z', 'A', 'B' ]

Conclusion

This approach efficiently compares arrays position by position, collecting differences and handling arrays of different lengths. It's useful for identifying character-level differences between sequences.

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

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements