JavaScript - find distance between items on array

In JavaScript, finding the distance between items in an array involves calculating the difference between each element and all succeeding elements. This creates a matrix of distances that can be useful for various algorithms and data analysis.

Suppose we have a sorted (increasing order) array of Numbers like this:

const arr = [2, 5, 7, 8, 9];

We need to write a JavaScript function that takes in one such array. The function should construct a new subarray for each element of the input array containing the differences between that element and all succeeding elements.

Understanding the Problem

For the first array element (2), the differences are:

5 - 2 = 3
7 - 2 = 5  
8 - 2 = 6
9 - 2 = 7

Therefore, the subarray for the first element should be:

[3, 5, 6, 7]

Similarly, for the second element (5):

[2, 3, 4]  // [7-5, 8-5, 9-5]

For the third element (7):

[1, 2]     // [8-7, 9-7]

For the fourth element (8):

[1]        // [9-8]

The last element has no succeeding elements, so it's excluded from the result.

Distance Calculation Between Array Elements Original Array: 2 5 7 8 9 Distance Subarrays: [2]: [3, 5, 6, 7] [5]: [2, 3, 4] [7]: [1, 2] [8]: [1] Example: Element 2 5 - 2 = 3 7 - 2 = 5 8 - 2 = 6 9 - 2 = 7 Result: [3, 5, 6, 7]

Using Recursive Approach

Here's a recursive solution that builds the distance matrix:

const arr = [2, 5, 7, 8, 9];

const distanceBetween = (arr, r = []) => {
    if (r.length <= arr.length - 2) {
        let temp = [];
        let b = arr[r.length];
        arr.forEach(e => temp.push(e - b));
        r.push(temp.filter(e => e > 0));
        return distanceBetween(arr, r);
    } else {
        return r;
    }
}

console.log(distanceBetween(arr));
[ [ 3, 5, 6, 7 ], [ 2, 3, 4 ], [ 1, 2 ], [ 1 ] ]

Using Iterative Approach

A simpler iterative approach that's easier to understand:

const arr = [2, 5, 7, 8, 9];

const findDistances = (array) => {
    const result = [];
    
    for (let i = 0; i < array.length - 1; i++) {
        const distances = [];
        for (let j = i + 1; j < array.length; j++) {
            distances.push(array[j] - array[i]);
        }
        result.push(distances);
    }
    
    return result;
}

console.log(findDistances(arr));
[ [ 3, 5, 6, 7 ], [ 2, 3, 4 ], [ 1, 2 ], [ 1 ] ]

Using map() Method

A functional programming approach using map():

const arr = [2, 5, 7, 8, 9];

const calculateDistances = (array) => {
    return array.slice(0, -1).map((current, index) => 
        array.slice(index + 1).map(next => next - current)
    );
}

console.log(calculateDistances(arr));
[ [ 3, 5, 6, 7 ], [ 2, 3, 4 ], [ 1, 2 ], [ 1 ] ]

Comparison

Method Readability Performance Use Case
Recursive Complex Good Academic/Interview
Iterative Excellent Best Production code
Functional (map) Good Good Functional programming

Conclusion

Finding distances between array elements creates a triangular matrix of differences. The iterative approach is most readable and efficient, while the functional approach offers a more declarative style for those preferring functional programming patterns.

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

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements