
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
Frequency of Elements in One Array that Appear in Another Array Using JavaScript
Problem
We are required to write a JavaScript function that takes in two arrays of strings. Our function should return the number of times each string of the second array appears in the first 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));
Output
[2, 1, 0]
Advertisements