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
Frequency of elements of one array that appear in another array using JavaScript
We need to write a JavaScript function that takes two arrays of strings and returns the frequency count of each element from the second array as it appears in the first array.
Problem
Given two arrays, we want to count how many times each string from the second array appears in the first array. The result should be an array of counts corresponding to each element in the second array.
Example
Following is the code ?
const arr1 = ['abc', 'abc', 'xyz', 'cde', 'uvw'];
const arr2 = ['abc', 'cde', 'uap'];
const findFrequency = (arr1 = [], arr2 = []) => {
const res = [];
let count = 0;
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if (arr2[i] === arr1[j]) {
count++;
}
}
res.push(count);
count = 0;
}
return res;
};
console.log(findFrequency(arr1, arr2));
[2, 1, 0]
How It Works
The function iterates through each element in the second array and counts its occurrences in the first array:
- 'abc' appears 2 times in arr1
- 'cde' appears 1 time in arr1
- 'uap' appears 0 times in arr1
Optimized Approach Using Map
For better performance with larger arrays, we can use a Map to store frequency counts:
const findFrequencyOptimized = (arr1 = [], arr2 = []) => {
// Create frequency map of arr1
const frequencyMap = new Map();
for (const element of arr1) {
frequencyMap.set(element, (frequencyMap.get(element) || 0) + 1);
}
// Get counts for arr2 elements
return arr2.map(element => frequencyMap.get(element) || 0);
};
const arr1 = ['abc', 'abc', 'xyz', 'cde', 'uvw'];
const arr2 = ['abc', 'cde', 'uap'];
console.log(findFrequencyOptimized(arr1, arr2));
[2, 1, 0]
Comparison
| Method | Time Complexity | Space Complexity |
|---|---|---|
| Nested Loops | O(m × n) | O(1) |
| Using Map | O(m + n) | O(m) |
Conclusion
Both approaches solve the problem effectively. The nested loop solution is simpler but less efficient for large datasets, while the Map-based approach offers better time complexity for larger arrays.
