Viết hàm tìm các phần tử chỉ xuất hiện ở 1 trong 2 mảng (symmetric difference).
Ví dụ
arr1: [12, 54, 2, 4, 6, 34, 3]
arr2: [54, 2, 5, 12, 4, 1, 3, 34]
Khác biệt: 6 (chỉ arr1), 5, 1 (chỉ arr2) → [6, 5, 1]
Giải pháp
Mã triển khai:
const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const difference = (first, second) => {
const set1 = new Set(first);
const set2 = new Set(second);
const res = [];
for (const x of first) if (!set2.has(x)) res.push(x);
for (const x of second) if (!set1.has(x)) res.push(x);
return res;
};
console.log(difference(arr1, arr2));
Kết quả
Đầu ra trong console:
[6, 5, 1]
Tối ưu: Dùng Set O(n) thay vì indexOf O(n²).