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

หาค่าที่ไม่ซ้ำกันในสองอาร์เรย์ (Symmetric Difference) - JavaScript

หาเอลีเมนต์ที่อยู่ในอาร์เรย์ใดอาร์เรย์หนึ่ง แต่ไม่อยู่ในทั้งสองอาร์เรย์ (Symmetric Difference) โดยใช้ indexOf ตรวจสอบ

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

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];

const unCommonArray = (first, second) => {
  const res = [];
  for (let i = 0; i < first.length; i++) {
    if (second.indexOf(first[i]) === -1) {
      res.push(first[i]);
    }
  }
  for (let j = 0; j < second.length; j++) {
    if (first.indexOf(second[j]) === -1) {
      res.push(second[j]);
    }
  }
  return res;
};

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

ผลลัพธ์

[ 6, 5, 1 ]

วิธีแก้ปัญหาแบบสมัยใหม่ (ES6+)

const unCommonArrayModern = (a, b) => [
  ...new Set(a.filter(x => !b.includes(x))),
  ...new Set(b.filter(x => !a.includes(x)))
];

ใช้ Set และ filter + includes เขียนสั้นกว่าและอ่านง่ายกว่า