# How to find the maximum distance between two occurrences of same number in array with JavaScript

16 views

```function GetMaxDistance(arr) {
let map = new Map();
let maximumDistance = 0;
const size = arr.length;

for (let i = 0; i < size; i++) {
if (!map.has(arr[i])) {
map.set(arr[i],i);
console.log("map[arr[i]]=" + map.get(arr[i]) + " arr[i]=" + arr[i] + " i=" + i);
}
else {
maximumDistance = Math.max(maximumDistance, i - map.get(arr[i]));
console.log("map[arr[i]]=" + map.get(arr[i]) + " i - map[arr[i]]=" + (i - map.get(arr[i])) + " i=" + i);
}
}
return maximumDistance;
}

const arr = [7, 1, 4, 3, 1, 5, 3, 4, 9, 1, 3];

console.log(GetMaxDistance(arr));

/*
run:

"map[arr[i]]=0 arr[i]=7 i=0"
"map[arr[i]]=1 arr[i]=1 i=1"
"map[arr[i]]=2 arr[i]=4 i=2"
"map[arr[i]]=3 arr[i]=3 i=3"
"map[arr[i]]=1 i - map[arr[i]]=3 i=4"
"map[arr[i]]=5 arr[i]=5 i=5"
"map[arr[i]]=3 i - map[arr[i]]=3 i=6"
"map[arr[i]]=2 i - map[arr[i]]=5 i=7"
"map[arr[i]]=8 arr[i]=9 i=8"
"map[arr[i]]=1 i - map[arr[i]]=8 i=9"
"map[arr[i]]=3 i - map[arr[i]]=7 i=10"
8

*/

```