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

Distance between 2 duplicate numbers in an array JavaScript


We are required to write a JavaScript function that takes in an array of numbers that contains at least one duplicate pair of numbers.

Our function should return the distance between all the duplicate pairs of numbers that exist in the array.

The code for this will be −

const arr = [2, 3, 4, 2, 5, 4, 1, 3];
const findDistance = arr => {
   var map = {}, res = {};
   arr.forEach((el, ind) => {
      map[el] = map[el] || [];
      map[el].push(ind);
   });
   Object.keys(map).forEach(el => {
      if (map[el].length > 1) {
         res[el] = Math.min.apply(null, map[el].reduce((acc, val, ind, arr) => {
            ind && acc.push(val - arr[ind - 1]);
            return acc;
         }, []));
      };
   });
   return res;
}
console.log(findDistance(arr));

Following is the output on console −

{ '2': 3, '3': 6, '4': 3 }