
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
Compare Two Arrays for Common Elements in JavaScript
Let’s say, we have two arrays, one contains the correct answer strings of some questions and one contains the answers attempted by a candidate, but somehow the arrays got shuffled and now they don’t have answers in corresponding order. But we can be sure that no two questions had the same answers.
Our job now is to write a function that takes these two arrays, checks them for common elements and finds all the common elements between them and then calculates the marks percentage of the candidate based on the count of common answers.
Let’s write the code for this function −
Example
const correct = ['India', 'Japan', 56, 'Mount Everest', 'Nile', 'Neil Armstrong', 'Inception', 'Lionel Messi', 'Joe Biden', 'Vatican City']; const answered = ['Nile', 'Neil Armstrong', 'Joe Biden', 'Mount Everest', 'Vatican City', 'Inception', 'Japan', 56, 'China', 'Cristiano Ronaldo']; const findPercentage = (first, second) => { const count = first.reduce((acc, val) => { if(second.includes(val)){ return ++acc; }; return acc; }, 0); return (count / first.length) * 100; }; console.log(`Candidate have scored ${findPercentage(correct, answered)}%`);
Output
The output in the console will be −
Candidate have scored 80%
Advertisements