최소한 하나의 중복 숫자 쌍을 포함하는 숫자 배열을 사용하는 JavaScript 함수를 작성해야 합니다.
우리의 함수는 배열에 존재하는 모든 중복 숫자 쌍 사이의 거리를 반환해야 합니다.
이에 대한 코드는 -
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)); 다음은 콘솔의 출력입니다 -
{ '2': 3, '3': 6, '4': 3 }