How to find distance between items on array JavaScript?

In JavaScript, finding the distance between array items means calculating how many positions separate two elements. The distance is measured as the absolute difference between their index positions.

Understanding the Problem

Array distance represents the number of steps needed to move from one element to another. For example, in the array [1, 2, 3, 4, 5], the distance between elements 2 and 4 is 2 because their indices are 1 and 3 respectively, giving us |3 - 1| = 2.

Basic Distance Calculation

The simplest approach uses indexOf() to find element positions and calculates the absolute difference:

function findDistance(arr, item1, item2) {
    let index1 = arr.indexOf(item1);
    let index2 = arr.indexOf(item2);
    
    // Handle case where elements don't exist
    if (index1 === -1 || index2 === -1) {
        return -1; // Elements not found
    }
    
    return Math.abs(index1 - index2);
}

const arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];

console.log("Distance between 10 and 50:", findDistance(arr, 10, 50));
console.log("Distance between 30 and 80:", findDistance(arr, 30, 80));
console.log("Distance between 20 and 20:", findDistance(arr, 20, 20));
Distance between 10 and 50: 4
Distance between 30 and 80: 5
Distance between 20 and 20: 0

Finding Distance Between All Occurrences

For arrays with duplicate elements, you might want to find distances between all possible pairs:

function findAllDistances(arr, item1, item2) {
    let indices1 = [];
    let indices2 = [];
    
    // Find all indices of both items
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === item1) indices1.push(i);
        if (arr[i] === item2) indices2.push(i);
    }
    
    let distances = [];
    
    // Calculate distances between all pairs
    for (let i of indices1) {
        for (let j of indices2) {
            distances.push(Math.abs(i - j));
        }
    }
    
    return distances;
}

const duplicateArr = [1, 2, 3, 2, 4, 2, 5];
console.log("All distances between 2 and 4:", findAllDistances(duplicateArr, 2, 4));
All distances between 2 and 4: [3, 1, 1]

Distance Between Index Positions

Sometimes you need distance between specific index positions rather than element values:

function distanceByIndex(arr, index1, index2) {
    // Validate indices
    if (index1 < 0 || index1 >= arr.length || 
        index2 < 0 || index2 >= arr.length) {
        return -1; // Invalid indices
    }
    
    return Math.abs(index1 - index2);
}

const numbers = [100, 200, 300, 400, 500];
console.log("Distance between index 1 and 4:", distanceByIndex(numbers, 1, 4));
console.log("Distance between index 0 and 2:", distanceByIndex(numbers, 0, 2));
Distance between index 1 and 4: 3
Distance between index 0 and 2: 2

Comparison of Methods

Method Use Case Time Complexity
indexOf() First occurrence only O(n)
All occurrences Duplicate elements O(n²)
Index-based Known positions O(1)

Practical Example

Here's a complete example that handles various scenarios:

function calculateDistance(arr, item1, item2, mode = 'first') {
    if (mode === 'first') {
        let index1 = arr.indexOf(item1);
        let index2 = arr.indexOf(item2);
        
        if (index1 === -1 || index2 === -1) {
            return null; // Element not found
        }
        
        return Math.abs(index1 - index2);
    }
    
    if (mode === 'closest') {
        let indices1 = arr.map((val, idx) => val === item1 ? idx : -1).filter(i => i !== -1);
        let indices2 = arr.map((val, idx) => val === item2 ? idx : -1).filter(i => i !== -1);
        
        if (indices1.length === 0 || indices2.length === 0) return null;
        
        let minDistance = Infinity;
        for (let i of indices1) {
            for (let j of indices2) {
                minDistance = Math.min(minDistance, Math.abs(i - j));
            }
        }
        
        return minDistance;
    }
}

const testArray = [5, 3, 8, 3, 1, 8, 9];
console.log("First occurrence distance:", calculateDistance(testArray, 3, 8, 'first'));
console.log("Closest distance:", calculateDistance(testArray, 3, 8, 'closest'));
First occurrence distance: 1
Closest distance: 1

Conclusion

Array distance calculation depends on your specific needs. Use indexOf() for simple cases, implement custom logic for duplicates, or use direct index calculation when positions are known. The time complexity ranges from O(1) to O(n²) depending on the approach.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements