Viết hàm so sánh hai mảng và tạo mảng thứ ba: lấy tất cả phần tử của mảng thứ hai, điền null cho các phần tử có trong mảng đầu tiên nhưng thiếu trong mảng thứ hai.
Ví dụ: arr1 = ['f','g','h'], arr2 = ['f','h'] → ['f', null, 'h'].
Mã thực hiện
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));
Kết quả
[ 'f', null, 'h' ]