Mô tả bài toán
Cho mảng tham chiếu arr1 và mảng arr2 (có thể thiếu phần tử). Tạo mảng kết quả cùng độ dài arr1: nếu phần tử tại vị trí i khớp thì lấy giá trị arr2, ngược lại null.
Ví dụ minh họa
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' ]
Phân tích logic
Biến offset bù trừ chỉ số khi arr2 thiếu phần tử. Khi arr1[i] != arr2[offset+i], giảm offset (vị trí arr2 lùi lại 1 so với arr1).
Cách viết rõ ràng hơn
const compareAndFill = (arr1, arr2) => {
let j = 0;
return arr1.map(el => {
if (j < arr2.length && el === arr2[j]) return arr2[j++];
return null;
});
};