Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 appear exactly twice in the array and return a new array of those elements.
Basic Approach Using Helper Function
The first approach uses a helper function to count occurrences of each element:
const arr = [0, 1, 2, 2, 3, 3, 5];
const findAppearances = (arr, num) => {
let count = 0;
for(let i = 0; i {
const res = [];
for(let i = 0; i
[2, 3]
Optimized Approach Using Map
A more efficient solution uses Map to count frequencies in a single pass:
const arr = [0, 1, 2, 2, 3, 3, 5];
const findElementsAppearingTwice = (arr) => {
const frequencyMap = new Map();
// Count frequencies
for(const element of arr) {
frequencyMap.set(element, (frequencyMap.get(element) || 0) + 1);
}
// Filter elements that appear exactly twice
const result = [];
for(const [element, count] of frequencyMap) {
if(count === 2) {
result.push(element);
}
}
return result;
};
console.log(findElementsAppearingTwice(arr));
[2, 3]
One-Liner Using Filter and Reduce
For a more functional approach, we can combine filter with frequency counting:
const arr = [0, 1, 2, 2, 3, 3, 5];
const getElementsAppearingTwice = (arr) => {
return [...new Set(arr.filter((item, index, array) =>
array.filter(x => x === item).length === 2
))];
};
console.log(getElementsAppearingTwice(arr));
[2, 3]
Comparison of Approaches
| Approach | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Helper Function | O(n²) | O(k) | High |
| Map Frequency | O(n) | O(n) | High |
| Filter Method | O(n²) | O(k) | Medium |
Testing with Different Arrays
// Test with strings
const stringArray = ['a', 'b', 'a', 'c', 'b', 'd'];
console.log("String array:", findElementsAppearingTwice(stringArray));
// Test with mixed types
const mixedArray = [1, '1', 1, 2, '1', 2];
console.log("Mixed array:", findElementsAppearingTwice(mixedArray));
// Test with no duplicates
const noDuplicates = [1, 2, 3, 4, 5];
console.log("No duplicates:", findElementsAppearingTwice(noDuplicates));
String array: [a, b] Mixed array: [1, 2] No duplicates: []
Conclusion
The Map-based approach offers the best performance with O(n) time complexity for finding elements that appear exactly twice. For small arrays, the helper function approach provides better readability, while the functional approach offers concise code at the cost of performance.
