Pair of similar elements at different indices in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Updated on 20-Jan-2021 06:57:53

Advertisements