Elements that appear twice in array in JavaScript


We are required to write a JavaScript function that takes in an array of literal values. Our function should pick all those values from the array that appears exactly twice in the array and return a new array of those elements.

Example

The code for this will be −

const arr = [0, 1, 2, 2, 3, 3, 5];
const findAppearances = (arr, num) => {
   let count = 0;
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(num !== el){
         continue;
      };
      count++;
   };
   return count;
};
const pickAppearingTwice = (arr = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(findAppearances(arr, el) === 2 && !res.includes(el)){
         res.push(el);
      };
   };
   return res;
};
console.log(pickAppearingTwice(arr));

Output

And the output in the console will be −

[2, 3]

Updated on: 23-Nov-2020

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements