JavaScript - find distance between items on array


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

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

We are required 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.

The sub-array should contain the difference (difference between that very element and the succeeding elements one by one) elements.

Therefore, for the first array element, 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, it should be −

[2, 3, 4]

For the third element −

[1, 2]

Fourth −

[1]

And since the fifth is the last element there will be no item left for it, so we are not considering the last element.

Therefore, the output for the full array should be −

const output = [
   [3, 5, 6, 7],
   [2, 3, 4],
   [1, 2],
   [1]
];

Example

The code for this will be −

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));

Output

And the output in the console will be −

[ [ 3, 5, 6, 7 ], [ 2, 3, 4 ], [ 1, 2 ], [ 1 ] ]

Updated on: 25-Nov-2020

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements