
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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' ]
- Related Articles
- Comparing corresponding values of two arrays in JavaScript
- Jasmine.js comparing arrays
- Comparing adjacent element and swap - JavaScript?
- Return the common filling value of two masked arrays in Numpy
- Complete Equation by Filling Missing Operator in JavaScript
- Comparing the performance of recursive and looped factorial function in JavaScript
- Comparing ascii scores of strings - JavaScript
- AND product of arrays in JavaScript
- Merging and rectifying arrays in JavaScript
- Comparing integers by taking two numbers in JavaScript
- Comparing forEach() and reduce() for summing an array of numbers in JavaScript.
- Comparing array elements keeping count in mind in JavaScript
- JavaScript Auto-filling one field same as other
- Compare and fill arrays - JavaScript
- Python Text Wrapping and Filling

Advertisements