- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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]
- Related Articles
- Frequency of elements of one array that appear in another array using JavaScript
- JavaScript array: Find all elements that appear more than n times
- Array elements that appear more than once in C?
- Array elements that appear more than once?
- Currified function that multiples array elements in JavaScript
- Why do backslashes appear twice while printing in Python?
- Find array elements that are out of order in JavaScript
- Rearranging array elements in JavaScript
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array in C++
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array in C++ program
- Consecutive elements sum array in JavaScript
- Alternatingly combining array elements in JavaScript
- How to replace elements in array with elements of another array in JavaScript?
- Finding upper elements in array in JavaScript
- Subtracting array in JavaScript Delete all those elements from the first array that are also included in the second array

Advertisements