Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาส่วนร่วมที่ไม่ซ้ำกัน (Unique Intersection) ของสองอาร์เรย์ใน JavaScript

เราต้องเขียนฟังก์ชันหาส่วนร่วม (intersection) ของสองอาร์เรย์ โดยค่าที่ซ้ำกันในทั้งสองอาร์เรย์จะนับเพียงครั้งเดียวในผลลัพธ์

ตัวอย่าง: arr1=[1,5,7,3,1], arr2=[1,7,3,1,6] → [1,3,7] (ลำดับไม่สำคัญ)

ตัวอย่างโค้ด

const arr1 = [1, 5, 7, 3, 1];
const arr2 = [1, 7, 3, 1, 6];

const uniqueIntersection = (arr1, arr2) => {
  const map = new Set();
  const res = [];
  arr1.forEach(el => map.add(el));
  arr2.forEach(el => {
    if (map.has(el)) { res.push(el); map.delete(el); }
  });
  return res;
};

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

ผลลัพธ์

ค่าที่แสดงในคอนโซลจะเป็นดังนี้:

[1, 7, 3]