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
Finding the missing number between two arrays of literals in JavaScript
Problem
We are required to write a JavaScript function that takes in two arrays arr1 and arr2.
arr2 is a shuffled duplicate of arr1 with just one element missing.
Our function should find and return that one element.
Example
Following is the code −
const arr1 = [6, 1, 3, 6, 8, 2];
const arr2 = [3, 6, 6, 1, 2];
const findMissing = (arr1 = [], arr2 = []) => {
const obj = {};
for (let i = 0; i < arr1.length; i++) {
if (obj[arr1[i]] === undefined) {
obj[arr1[i]] = 1;
} else {
obj[arr1[i]]++;
};
}
for (let i = 0; i < arr2.length; i++) {
if (obj[arr2[i]] === undefined || obj[arr2[i]]-- === 0) {
return arr2[i];
}
}
for (key in obj) {
if (obj[key] > 0) {
return Number(key);
}
}
return -1;
};
console.log(findMissing(arr1, arr2));
Output
Following is the console output −
8
Advertisements