Computer >> Computer tutorials >  >> Programming >> Javascript

How to find distance between items on array JavaScript


We are required to write a function, say arrayDistance() that takes in an array of Numbers and returns another array with elements as the difference between two consecutive elements from the original array.

For example, if the input array is −

const arr = [1000,2000,5000,4000,300,0,1250];

Then the output would be −

[(1000-2000),(2000-5000),(5000-4000),(4000-300),(300-0),(0-1250)]

Therefore, let’s write the code for this function −

Example

const arr = [1000,2000,5000,4000,300,0,1250];
const arrayDistance = arr => {
   return arr.reduce((acc, val, ind) => {
      if(arr[ind+1] !== undefined){
         return acc.concat(Math.abs(val-arr[ind+1]));
      }else{
         return acc;
      }
   }, []);
};
console.log(arrayDistance(arr));

Output

The output in the console will be −

[ 1000, 3000, 1000, 3700, 300, 1250 ]