Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tìm giao của 2 mảng chuỗi - JavaScript

Viết hàm tìm giao của 2 mảng chuỗi: phần tử xuất hiện trong cả 2, số lần = min(count1, count2).

Ví dụ

arr1: ['hello', 'world', 'how', 'are', 'you']

arr2: ['hey', 'world', 'can', 'you', 'rotate']

Giao: ['world', 'you']

Giải pháp

Mã triển khai (tối ưu: duyệt mảng nhỏ hơn):

const arr1 = ['hello', 'world', 'how', 'are', 'you'];
const arr2 = ['hey', 'world', 'can', 'you', 'rotate'];

const intersectElements = (arr1, arr2) => {
  const res = [];
  const smaller = arr1.length < arr2.length ? arr1 : arr2;
  const bigger = arr1.length >= arr2.length ? [...arr1] : [...arr2]; // Copy
  
  for (const item of smaller) {
    const idx = bigger.indexOf(item);
    if (idx !== -1) {
      res.push(item);
      bigger.splice(idx, 1); // Xóa để không đếm trùng
    }
  }
  return res;
};

console.log(intersectElements(arr1, arr2));

Kết quả

Đầu ra trong console:

['world', 'you']