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 −

 Live Demo

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

Updated on: 17-Apr-2021

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements