

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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]
- Related Questions & Answers
- Array elements that appear more than once?
- Frequency of elements of one array that appear in another array using JavaScript
- Array elements that appear more than once in C?
- JavaScript array: Find all elements that appear more than n times
- Why do backslashes appear twice while printing in Python?
- Currified function that multiples array elements in JavaScript
- Find array elements that are out of order in JavaScript
- Finding two missing numbers that appears only once and twice respectively in JavaScript
- Return the index of first character that appears twice in a string in JavaScript
- Twice join of two strings in JavaScript
- Sorting Array Elements 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++
- Twice repetitive word count in a string - JavaScript
- Find the element that appears once in an array where every other element appears twice in C++
Advertisements