
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pair of Similar Elements at Different Indices in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.
The function is required to count the number of all such element pairs from the array that are equal in magnitude but are present at different indices.
For example −
If the input array is −
const arr = [7, 9, 5, 7, 7, 5];
Then the output should be −
const output = 4;
because the desired pairs are [7, 7], [7, 7], [7, 7], [5, 5]
Example
Following is the code −
const arr = [7, 9, 5, 7, 7, 5]; const equalPairCount = (arr = []) => { if(!arr?.length){ return 0; }; const map = {} let count = 0; arr.forEach((val) => { if (map[val]) { count += map[val]; }; map[val] = map[val] + 1 || 1; }); return count; }; console.log(equalPairCount(arr));
Output
Following is the console output −
4
Advertisements