Thursday, November 30, 2023

Pair check in Javascript

 

const arr = [1, 5, 2, 1, 6, 2, 2, 9];
const countPairs = (arr = []) => {
   const { length } = arr;
   let count = 0;
   // making a shallow copy so that the original array remains unaltered
   const copy = arr.slice();
   copy.sort((a, b) => a - b);
   for(let i = 0; i < length; i++){
      if(copy[i] === copy[i + 1]){
         i++;
         count++;
      };
   };
   return count;
};
console.log(countPairs(arr));

No comments:

Post a Comment