- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Distance between 2 duplicate numbers in an array JavaScript
We are required to write a JavaScript function that takes in an array of numbers that contains at least one duplicate pair of numbers.
Our function should return the distance between all the duplicate pairs of numbers that exist in the array.
The code for this will be −
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));
Following is the output on console −
{ '2': 3, '3': 6, '4': 3 }
Advertisements