Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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'];
Algorithm Approach
The solution uses an offset variable to track the position in the second array. When elements match, we include them; when they don't, we insert null and adjust the offset to account for the missing element.
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' ]
Alternative Approach Using includes()
Here's another way to solve this problem using the includes() method:
const arr1 = ['f', 'g', 'h'];
const arr2 = ['f', 'h'];
const compareAndFillSimple = (arr1, arr2) => {
let arr2Index = 0;
return arr1.map(element => {
if (arr2Index
[ 'f', null, 'h' ]
How It Works
The function iterates through the first array and checks if each element matches the current position in the second array. When a match is found, it returns the element and advances the pointer in the second array. When no match is found, it returns null.
Conclusion
This approach efficiently compares two arrays and fills missing positions with null values. The offset-based method maintains the relative order of elements from the second array.
