
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Give two different examples of pair of (i) similar figures.(ii)non-similar figures.
- Give two different examples of pair of non-similar figures.
- Difference of digits at alternate indices in JavaScript
- MongoDB aggregation of elements with similar ids in different documents?
- Python program to remove elements at Indices in List
- Cumulative average of pair of elements in JavaScript
- Python Program to repeat elements at custom indices
- Python Group elements at same indices in a multi-list
- Sum all similar elements in one array - JavaScript
- Find the Maximum of Similar Indices in two list of Tuples in Python
- Return an array of all the indices of minimum elements in the array in JavaScript
- Parts of array with n different elements in JavaScript
- Python – Grouped Consecutive Range Indices of Elements
- Find elements of a list by indices in Python
- Return an array formed from the elements of a masked array at the given indices in NumPy

Advertisements