- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 and fill arrays - 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'];
Example
Following is the code −
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
This will produce the following output on console −
[ 'f', null, 'h' ]
- Related Articles
- How to compare arrays in JavaScript?
- Compare arrays using Array.prototype.every() in JavaScript
- Compare two arrays of single characters and return the difference? JavaScript
- Compare two arrays and get those values that did not match JavaScript
- How to compare two arrays in JavaScript and make a new one of true and false? JavaScript
- How to compare two string arrays, case insensitive and independent about ordering JavaScript, ES6
- Compare Two Java long Arrays
- Compare Two Java double arrays
- How to compare two arrays when the key is a string - JavaScript
- How to compare arrays in Java
- How to compare two arrays in C#?
- How to compare two arrays in Java?
- Java Program to compare two Boolean Arrays
- Java Program to compare two Byte Arrays
- Compare Two Java int Arrays in Java

Advertisements