
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
Advertisements