数组JavaScript中两个重复数字之间的距离
我们需要编写一个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 }热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短