เราต้องเขียนฟังก์ชัน 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 }