
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
Comparing and Filling Arrays in JavaScript
We are required to write a function that compares two arrays and creates a third array filling that array with all the elements of the second array and filling null for all those elements that are present in the first array but misses out in the second array.
For example:
If the two arrays are −
const arr1 = ['f', 'g', 'h']; const arr2 = ['f', 'h'];
Then the output should be −
const output = ['f', null, 'h'];
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr1 = ['f', 'g', 'h']; const arr2 = ['f', 'h']; const compareAndFill = (arr1, arr2) => { let offset = 0; const res = arr1.map((el, i) => { if (el === arr2[offset + i]) { return el; }; offset--; return null; }); return res; }; console.log(compareAndFill(arr1, arr2));
Output
The output in the console will be −
[ 'f', null, 'h' ]
Advertisements