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

วิธีหาค่าซ้ำในอาร์เรย์ JavaScript

เพื่อหาค่าซ้ำ (duplicate values) ในอาร์เรย์ JavaScript สามารถใช้วิธีต่างๆ ได้ ตัวอย่างด้านล่างใช้ Object เพื่อเก็บค่าที่ไม่ซ้ำ แล้วคืนค่าเป็นอาร์เรย์ที่ไม่มีค่าซ้ำ

ตัวอย่าง (ลบค่าซ้ำ / หาค่าที่ไม่ซ้ำ)

<html>
  <body>
    <script>
      function removeDuplicate(arr) {
        var c;
        var len = arr.length;
        var result = [];
        var obj = {};

        for (c = 0; c < len; c++) {
          obj[arr[c]] = 0; // ใช้ key ของ object เพื่อดักค่าซ้ำ
        }

        for (c in obj) {
          result.push(c);
        }

        return result;
      }

      var myArr = [10, 20, 30, 40, 10, 40, 70, 80, 70, 90];
      document.write(removeDuplicate(myArr));
    </script>
  </body>
</html>

ผลลัพธ์

10,20,30,40,70,80,90

วิธีทันสมัยกว่า (ES6+)

// 1. ใช้ Set (ง่ายที่สุด สร้างอาร์เรย์ใหม่ไม่ซ้ำ)
const unique = [...new Set(myArr)];

// 2. ใช้ filter + indexOf
const unique2 = myArr.filter((item, index) => myArr.indexOf(item) === index);

// 3. หาค่าที่ซ้ำจริงๆ (ค่าที่ปรากฏมากกว่า 1 ครั้ง)
const duplicates = myArr.filter((item, index) => myArr.indexOf(item) !== index);
// ผลลัพธ์: [10, 40, 70, 10, 40, 70]

// 4. หาค่าซ้ำแบบไม่ซ้ำกัน (unique duplicates)
const uniqueDuplicates = [...new Set(myArr.filter((item, index) => myArr.indexOf(item) !== index))];
// ผลลัพธ์: [10, 40, 70]

หมายเหตุ: ตัวอย่างเดิมคืนค่าเป็นสตริง (เพราะ key ของ object เป็นสตริง) วิธี ES6 คงชนิดข้อมูลได้ดีกว่า