เราต้องเขียนฟังก์ชันที่เปรียบเทียบสองอาร์เรย์และสร้างอาร์เรย์ที่สามโดยเติมด้วยองค์ประกอบทั้งหมดของอาร์เรย์ที่สอง และเติม null สำหรับองค์ประกอบที่มีอยู่ในอาร์เรย์แรกแต่หายไปในอาร์เรย์ที่สอง
ตัวอย่างเช่น:
ถ้าสองอาร์เรย์คือ:
const arr1 = ['f', 'g', 'h']; const arr2 = ['f', 'h'];
ผลลัพธ์ควรเป็น:
const output = ['f', null, 'h'];
ตัวอย่าง
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));
ผลลัพธ์
โค้ดนี้จะแสดงผลลัพธ์ดังต่อไปนี้บนคอนโซล:
[ 'f', null, 'h' ]