数组中两个重复数字之间的距离 JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/16 15:40:17

我们需要编写一个 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 }

相关文章


有用资源