# Pair of similar elements at different indices in JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

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